Fixing the monitoring tasks

revert-70aa11f8
geethkokila 9 years ago
parent b298407160
commit 6d687364c6

@ -245,14 +245,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
}
for (Device device : allDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
DeviceManagementService managementService = this.getPluginRepository().
getDeviceManagementService(device.getType());
if(managementService != null) {
Device dmsDevice = managementService.getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (dmsDevice != null) {
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
}
}
devices.add(device);
}
return devices;
@ -278,14 +280,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
for (Device device : allDevices) {
Device dmsDevice =
this.getPluginRepository().getDeviceManagementService(
device.getType()).getDeviceManager().getDevice(
DeviceManagementService service = this.getPluginRepository().getDeviceManagementService(device.getType());
if (service != null) {
Device dmsDevice = service.getDeviceManager().getDevice(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
if (dmsDevice != null) {
device.setFeatures(dmsDevice.getFeatures());
device.setProperties(dmsDevice.getProperties());
}
}
devices.add(device);
}
return devices;
@ -307,7 +311,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
String subject = "";
for (NotificationMessages notificationMessage : notificationMessages) {
if (org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailNotifications.ENROL_NOTIFICATION_TYPE.equals(
if (org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailNotifications.ENROL_NOTIFICATION_TYPE
.equals(
notificationMessage.getType())) {
messageHeader = notificationMessage.getHeader();
messageBody = notificationMessage.getBody();

@ -67,6 +67,8 @@ public interface PolicyManagerService {
int getPolicyCount() throws PolicyManagementException;
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException;

@ -34,7 +34,9 @@ import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.impl.PolicyInformationPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.MonitoringManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl;
@ -47,10 +49,12 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
PolicyAdministratorPointImpl policyAdministratorPoint;
MonitoringManager monitoringManager;
private PolicyManager policyManager;
public PolicyManagerServiceImpl() {
policyAdministratorPoint = new PolicyAdministratorPointImpl();
monitoringManager = new MonitoringManagerImpl();
policyManager = new PolicyManagerImpl();
}
@Override
@ -215,6 +219,11 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
return policyAdministratorPoint.getPolicyCount();
}
@Override
public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
return policyManager.getAppliedPolicyToDevice(deviceIdentifier);
}
@Override
public List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException {

@ -22,13 +22,24 @@ package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface MonitoringDAO {
int addComplianceDetails(int deviceId, int policyId) throws MonitoringDAOException;
/**
* This is getting a list of values with device id and applied policy
* @param devicePolicyMap <Device Id, Policy Id>
* @throws MonitoringDAOException
*/
void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException;
int setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException;
void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException;
int setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException;
void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature>
complianceFeatures)

@ -25,6 +25,7 @@ import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyCriterion;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.HashMap;
import java.util.List;
public interface PolicyDAO {
@ -104,4 +105,6 @@ public interface PolicyDAO {
int getAppliedPolicyId(int deviceId) throws PolicyManagerDAOException;
Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException;
}
HashMap<Integer, Integer> getAppliedPolicyIds(List<Integer> deviceIds) throws PolicyManagerDAOException;
}

@ -28,33 +28,31 @@ import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException;
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.util.PolicyManagementDAOUtil;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.*;
public class MonitoringDAOImpl implements MonitoringDAO {
private static final Log log = LogFactory.getLog(MonitoringDAOImpl.class);
@Override
public int setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException {
public int addComplianceDetails(int deviceId, int policyId) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, LAST_FAILED_TIME, " +
"ATTEMPTS) VALUES (?, ?, ?, ?, ?) ";
String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " +
"LAST_REQUESTED_TIME) VALUES (?, ?, ?,?, ?) ";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId);
stmt.setInt(2, policyId);
stmt.setInt(3, 0);
stmt.setTimestamp(4, currentTimestamp);
stmt.setInt(5, 0);
stmt.setInt(3, 1);
stmt.setInt(4, 1);
stmt.setTimestamp(5, currentTimestamp);
stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys();
@ -71,32 +69,109 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
}
@Override
public void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " +
"LAST_REQUESTED_TIME) VALUES (?, ?, ?,?, ?) ";
stmt = conn.prepareStatement(query);
for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) {
stmt.setInt(1, map.getKey());
stmt.setInt(2, map.getValue());
stmt.setInt(3, 1);
stmt.setInt(4, 1);
stmt.setTimestamp(5, currentTimestamp);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
String msg = "Error occurred while adding the none compliance to the database.";
log.error(msg, e);
throw new MonitoringDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
}
@Override
public int setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
try {
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 = ?," +
" ATTEMPTS=0 WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, policyId);
stmt.setInt(3, deviceId);
stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
return generatedKeys.getInt(1);
} else {
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while updating the none compliance to the database.";
log.error(msg, e);
throw new MonitoringDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
}
@Override
public void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException {
public int setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" +
" WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query);
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, 1);
stmt.setTimestamp(2, currentTimestamp);
stmt.setInt(3, deviceId);
stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
return generatedKeys.getInt(1);
} else {
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while deleting the none compliance to the database.";
log.error(msg, e);
throw new MonitoringDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
}
}
@ -171,13 +246,13 @@ public class MonitoringDAOImpl implements MonitoringDAO {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<ComplianceData> complianceDataList = null;
List<ComplianceData> complianceDataList = new ArrayList<>();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID IN (?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, makeString(deviceIds));
stmt.setString(1, PolicyManagerUtil.makeString(deviceIds));
resultSet = stmt.executeQuery();
@ -348,13 +423,5 @@ public class MonitoringDAOImpl implements MonitoringDAO {
}
}
private String makeString(List<Integer> values) {
StringBuilder buff = new StringBuilder();
for (int value : values) {
buff.append(value).append(",");
}
buff.deleteCharAt(buff.length() - 1);
return buff.toString();
}
}

@ -38,10 +38,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.*;
public class PolicyDAOImpl implements PolicyDAO {
@ -755,16 +752,18 @@ public class PolicyDAOImpl implements PolicyDAO {
Connection conn;
PreparedStatement stmt = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_DEVICE_POLICY_APPLIED " +
"(DEVICE_ID, POLICY_ID, POLICY_CONTENT, CREATED_TIME, UPDATED_TIME) VALUES (?, ?, ?, ?, ?)";
String query = "INSERT INTO DM_DEVICE_POLICY_APPLIED (DEVICE_ID, POLICY_ID, POLICY_CONTENT, " +
"CREATED_TIME, UPDATED_TIME, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId);
stmt.setInt(2, policyId);
stmt.setObject(3, profileFeatures);
stmt.setTimestamp(4, currentTimestamp);
stmt.setTimestamp(5, currentTimestamp);
stmt.setInt(6, tenantId);
stmt.executeUpdate();
@ -1246,6 +1245,7 @@ public class PolicyDAOImpl implements PolicyDAO {
resultSet = stmt.executeQuery();
while (resultSet.next()) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
byte[] contentBytes;
@ -1270,6 +1270,7 @@ public class PolicyDAOImpl implements PolicyDAO {
}
}
}
}
} catch (SQLException e) {
String msg = "Error occurred while getting the applied policy.";
@ -1290,4 +1291,37 @@ public class PolicyDAOImpl implements PolicyDAO {
return policy;
}
@Override
public HashMap<Integer, Integer> getAppliedPolicyIds(List<Integer> deviceIds) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
HashMap<Integer, Integer> devicePolicyIds = new HashMap<>();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE DEVICE_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, PolicyManagerUtil.makeString(deviceIds));
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
devicePolicyIds.put(resultSet.getInt("DEVICE_ID"), resultSet.getInt("POLICY_ID"));
}
} catch (SQLException e) {
String msg = "Error occurred while getting the applied policy.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
this.closeConnection();
}
return devicePolicyIds;
}
}

@ -24,12 +24,16 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
@ -45,6 +49,7 @@ import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.util.*;
@ -73,10 +78,13 @@ public class MonitoringManagerImpl implements MonitoringManager {
List<ComplianceFeature> complianceFeatures;
try {
PolicyManagementDAOFactory.beginTransaction();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
Policy policy = policyDAO.getAppliedPolicy(device.getId());
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
PolicyManager manager = new PolicyManagerImpl();
Device device = service.getDevice(deviceIdentifier);
Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); //policyDAO.getAppliedPolicy(device
// .getId());
PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance().
getPolicyMonitoringService(deviceIdentifier.getType());
@ -84,9 +92,12 @@ public class MonitoringManagerImpl implements MonitoringManager {
policy, deviceResponse);
complianceData.setPolicy(policy);
complianceFeatures = complianceData.getComplianceFeatures();
complianceData.setDeviceId(device.getId());
complianceData.setPolicyId(policy.getId());
if (!complianceFeatures.isEmpty()) {
int complianceId = monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId());
complianceData.setId(complianceId);
monitoringDAO.addNoneComplianceFeatures(complianceId, device.getId(), complianceFeatures);
complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData);
List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList();
@ -99,11 +110,13 @@ public class MonitoringManagerImpl implements MonitoringManager {
}
} else {
monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId());
int complianceId = monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId());
complianceData.setId(complianceId);
monitoringDAO.deleteNoneComplianceData(complianceId);
}
PolicyManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
} catch (DeviceManagementException e) {
try {
PolicyManagementDAOFactory.rollbackTransaction();
} catch (PolicyManagerDAOException e1) {
@ -133,6 +146,16 @@ public class MonitoringManagerImpl implements MonitoringManager {
getId() + " - " + deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
} catch (PolicyManagementException e) {
try {
PolicyManagementDAOFactory.rollbackTransaction();
} catch (PolicyManagerDAOException e1) {
log.warn("Error occurred while roll backing the transaction.");
}
String msg = "Unable tor retrieve policy data from DB for device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
return complianceFeatures;
}
@ -142,14 +165,15 @@ public class MonitoringManagerImpl implements MonitoringManager {
public boolean isCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
//deviceDAO.getDevice(deviceIdentifier, tenantId);
ComplianceData complianceData = monitoringDAO.getCompliance(device.getId());
if (complianceData == null || !complianceData.isStatus()) {
return false;
}
} catch (DeviceManagementDAOException e) {
} catch (DeviceManagementException e) {
String msg = "Unable to retrieve device data for " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
@ -170,14 +194,14 @@ public class MonitoringManagerImpl implements MonitoringManager {
ComplianceData complianceData;
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Device device = deviceDAO.getDevice(deviceIdentifier, tenantId);
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
complianceData = monitoringDAO.getCompliance(device.getId());
List<ComplianceFeature> complianceFeatures =
monitoringDAO.getNoneComplianceFeatures(complianceData.getId());
complianceData.setComplianceFeatures(complianceFeatures);
} catch (DeviceManagementDAOException e) {
} catch (DeviceManagementException e) {
String msg = "Unable to retrieve device data for " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
@ -196,6 +220,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException {
try {
PolicyManagementDAOFactory.beginTransaction();
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
@ -206,15 +231,19 @@ public class MonitoringManagerImpl implements MonitoringManager {
deviceIds.put(device.getId(), device);
}
List<ComplianceData> complianceDatas = monitoringDAO.getCompliance(new ArrayList<>(deviceIds.keySet()));
List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet());
List<ComplianceData> complianceDatas = monitoringDAO.getCompliance(deviceIDs);
HashMap<Integer, Integer> devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs);
Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
Map<Integer, Device> inactiveDeviceIds = new HashMap<>();
Map<Integer, Integer> firstTimeDeviceId = new HashMap<>();
Map<Integer, ComplianceData> tempMap = new HashMap<>();
if (complianceDatas != null || !complianceDatas.isEmpty()) {
for (ComplianceData complianceData : complianceDatas) {
tempMap.put(complianceData.getDeviceId(), complianceData);
@ -231,15 +260,18 @@ public class MonitoringManagerImpl implements MonitoringManager {
deviceIds.get(complianceData.getDeviceId()));
}
}
}
for (Device device : devices) {
if (!tempMap.containsKey(device.getId())) {
deviceIdsToAddOperation.put(device.getId(), device);
firstTimeDeviceId.put(device.getId(), devicePolicyIdMap.get(device.getId()));
}
}
if (!deviceIdsToAddOperation.isEmpty()) {
this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values()));
monitoringDAO.addComplianceDetails(firstTimeDeviceId);
}
if (!deviceIdsWithExistingOperation.isEmpty()) {
@ -248,14 +280,35 @@ public class MonitoringManagerImpl implements MonitoringManager {
new ArrayList<>(deviceIdsWithExistingOperation.values())));
}
PolicyManagementDAOFactory.commitTransaction();
} catch (MonitoringDAOException e) {
try {
PolicyManagementDAOFactory.rollbackTransaction();
} catch (PolicyManagerDAOException e1) {
log.warn("Error occurred while roll backing the transaction.");
}
String msg = "Error occurred from monitoring dao.";
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
} catch (OperationManagementException e) {
try {
PolicyManagementDAOFactory.rollbackTransaction();
} catch (PolicyManagerDAOException e1) {
log.warn("Error occurred while roll backing the transaction.");
}
String msg = "Error occurred while adding monitoring operation to devices";
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
} catch (PolicyManagerDAOException e) {
try {
PolicyManagementDAOFactory.rollbackTransaction();
} catch (PolicyManagerDAOException e1) {
log.warn("Error occurred while roll backing the transaction.");
}
String msg = "Error occurred reading the applied policies to devices.";
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
}
}
@ -269,8 +322,11 @@ public class MonitoringManagerImpl implements MonitoringManager {
monitoringOperation.setEnabled(true);
monitoringOperation.setType(Operation.Type.COMMAND);
monitoringOperation.setCode(OPERATION_MONITOR);
PolicyManagementDataHolder.getInstance().getDeviceManagementService().
addOperation(monitoringOperation, deviceIdentifiers);
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
service.addOperation(monitoringOperation, deviceIdentifiers);
// PolicyManagementDataHolder.getInstance().getDeviceManagementService().
// addOperation(monitoringOperation, deviceIdentifiers);
}
private List<DeviceIdentifier> getDeviceIdentifiersFromDevices(List<Device> devices) {

@ -116,6 +116,11 @@ public class PolicyManagementService implements PolicyManagerService {
return policyManagerService.getPolicyCount();
}
@Override
public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
return policyManagerService.getAppliedPolicyToDevice(deviceIdentifier);
}
@Override
public List<ComplianceFeature> CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException {
@ -123,7 +128,8 @@ public class PolicyManagementService implements PolicyManagerService {
}
@Override
public boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException {
public boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws
PolicyComplianceException {
return policyManagerService.checkCompliance(deviceIdentifier, response);
}

@ -89,4 +89,13 @@ public class PolicyManagerUtil {
return dataSource;
}
public static String makeString(List<Integer> values) {
StringBuilder buff = new StringBuilder();
for (int value : values) {
buff.append(value).append(",");
}
buff.deleteCharAt(buff.length() - 1);
return buff.toString();
}
}

@ -24,7 +24,10 @@ import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.w3c.dom.Document;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.common.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
@ -53,6 +56,35 @@ public abstract class BasePolicyManagementDAOTest {
this.dataSource = this.getDataSource(this.readDataSourceConfig());
DeviceManagementDAOFactory.init(dataSource);
PolicyManagementDAOFactory.init(dataSource);
OperationManagementDAOFactory.init(dataSource);
}
public void initiatePriviledgeCaronContext() throws Exception {
if (System.getProperty("carbon.home") == null) {
File file = new File("src/test/resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
}
@BeforeClass

@ -0,0 +1,189 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.MonitoringManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.services.PolicyMonitoringServiceTest;
import org.wso2.carbon.policy.mgt.core.task.MonitoringTask;
import java.util.List;
public class MonitoringTestCase extends BasePolicyManagementDAOTest {
private static final Log log = LogFactory.getLog(MonitoringTestCase.class);
private static final String ANDROID = "android";
DeviceIdentifier identifier = new DeviceIdentifier();
@BeforeClass
@Override
public void init() throws Exception {
}
@Test
public void testMonitorDao() throws PolicyManagementException, DeviceManagementException {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
List<Policy> policies = policyManagerService.getPolicies(ANDROID);
List<Device> devices = service.getAllDevices(ANDROID);
for (Policy policy : policies) {
log.debug(policy.getPolicyName() + "-----P");
}
for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- D");
}
identifier.setType(ANDROID);
identifier.setId(devices.get(0).getDeviceIdentifier());
PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl();
administratorPoint.setPolicyUsed(identifier, policies.get(0));
}
@Test(dependsOnMethods = ("testMonitorDao"))
public void getDeviceAppliedPolicy() throws PolicyManagementException {
PolicyManager manager = new PolicyManagerImpl();
Policy policy = manager.getAppliedPolicyToDevice(identifier);
log.debug(policy.getId());
log.debug(policy.getPolicyName());
log.debug(policy.getCompliance());
}
@Test(dependsOnMethods = ("testMonitorDao"))
public void addComplianceOperation() throws PolicyManagementException, DeviceManagementException,
PolicyComplianceException {
log.debug("Compliance operations adding started.");
PolicyManager manager = new PolicyManagerImpl();
Policy policy = manager.getAppliedPolicyToDevice(identifier);
OperationManager operationManager = new OperationManagerImpl();
DeviceManagementDataHolder.getInstance().setOperationManager(operationManager);
log.debug(policy.getId());
log.debug(policy.getPolicyName());
log.debug(policy.getCompliance());
MonitoringManager monitoringManager = new MonitoringManagerImpl();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> devices = service.getAllDevices(ANDROID);
monitoringManager.addMonitoringOperation(devices);
log.debug("Compliance operations adding done.");
}
@Test(dependsOnMethods = ("addComplianceOperation"))
public void checkComplianceFromMonitoringService() throws PolicyManagementException, DeviceManagementException,
PolicyComplianceException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
monitoringServiceTest);
DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl();
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
List<Device> devices = adminService.getAllDevices();
monitoringServiceTest.notifyDevices(devices);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(devices.get(0).getDeviceIdentifier());
deviceIdentifier.setType(devices.get(0).getType());
Policy policy = policyManagerService.getAppliedPolicyToDevice(deviceIdentifier);
Object ob = new Object();
// 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"))
public void checkCompliance() throws DeviceManagementException, PolicyComplianceException {
DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl();
List<Device> devices = adminService.getAllDevices();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(devices.get(0).getDeviceIdentifier());
deviceIdentifier.setType(devices.get(0).getType());
Object ob = new Object();
MonitoringManager monitoringManager = new MonitoringManagerImpl();
monitoringManager.checkPolicyCompliance(deviceIdentifier, ob);
}
}

@ -21,14 +21,14 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
@ -39,7 +39,6 @@ import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl;
import org.wso2.carbon.policy.mgt.core.util.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@ -57,38 +56,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Override
public void init() throws Exception {
initDatSource();
System.setProperty("GetTenantIDForTest", "Super");
this.setUp();
}
public void setUp() throws Exception {
if (System.getProperty("carbon.home") == null) {
File file = new File("src/test/resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
file = new File("../../../resources/carbon-home");
if (file.exists()) {
System.setProperty("carbon.home", file.getAbsolutePath());
}
// System.setProperty("GetTenantIDForTest", "Super");
initiatePriviledgeCaronContext();
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants
.SUPER_TENANT_DOMAIN_NAME);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
}
@Test
public void addDeviceType() throws DeviceManagementDAOException {
@ -98,16 +69,37 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addDeviceType"))
public void addDevice() throws DeviceManagementDAOException {
public void addDevice() throws DeviceManagementDAOException, DeviceManagementException {
DeviceDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceDAO();
DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
DeviceType type = DeviceTypeCreator.getDeviceType();
devices = DeviceCreator.getDeviceList(type);
for (Device device : devices) {
int id = deviceTypeDAO.addDevice(type.getId(), device, -1234);
int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234);
}
List<Device> devices = deviceDAO.getDevices(-1234);
for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- X");
}
List<Device> devices2 = deviceDAO.getDevices("android", -1234);
for (Device device : devices2) {
log.debug(device.getDeviceIdentifier() + " ----- XX");
}
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> devices3 = service.getAllDevices("android");
for (Device device : devices3) {
log.debug(device.getDeviceIdentifier() + " ----- XXX");
}
}
@ -354,4 +346,23 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
}
@Test(dependsOnMethods = ("deletPolicy"))
public void testMonitorDao() throws PolicyManagementException, DeviceManagementException {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
List<Policy> policies = policyManagerService.getPolicies("android");
List<Device> devices = service.getAllDevices("android");
for (Policy policy : policies) {
log.debug(policy.getPolicyName() + "-----P");
}
for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- D");
}
}
}

@ -0,0 +1,84 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.mgt.core.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import java.util.ArrayList;
import java.util.List;
public class PolicyMonitoringServiceTest implements PolicyMonitoringService {
private static final Log log = LogFactory.getLog(PolicyMonitoringServiceTest.class);
@Override
public void notifyDevices(List<Device> devices) throws PolicyComplianceException {
log.debug("Device notifying is called by the task.");
}
@Override
public ComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response)
throws PolicyComplianceException {
log.debug("Check compliance is called.");
log.debug(policy.getPolicyName());
log.debug(policy.getId());
log.debug(deviceIdentifier.getId());
log.debug(deviceIdentifier.getType());
ComplianceData data = new ComplianceData();
List<ComplianceFeature> complianceFeatures = new ArrayList<>();
// List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList();
// for (ProfileFeature pf : profileFeatures) {
// log.debug(pf.getFeatureCode());
// ComplianceFeature comf = new ComplianceFeature();
//
// comf.setFeatureCode(pf.getFeatureCode());
// comf.setCompliance(false);
// comf.setMessage("This is a test....");
//
// complianceFeatures.add(comf);
// }
data.setComplianceFeatures(complianceFeatures);
data.setStatus(false);
return data;
}
@Override
public String getType() {
return "android";
}
}

@ -246,6 +246,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
DEVICE_ID INT NOT NULL ,
POLICY_ID INT NOT NULL ,
POLICY_CONTENT BLOB NULL ,
TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL ,
CREATED_TIME TIMESTAMP NULL ,
UPDATED_TIME TIMESTAMP NULL ,

@ -26,6 +26,7 @@
<parameter name="dbType" value="H2"/>
<classes>
<class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/>
<class name="org.wso2.carbon.policy.mgt.core.MonitoringTestCase" />
</classes>
</test>
</suite>

@ -222,6 +222,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
DEVICE_ID INT NOT NULL ,
POLICY_ID INT NOT NULL ,
POLICY_CONTENT BLOB NULL ,
TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL ,
CREATED_TIME TIMESTAMP NULL ,
UPDATED_TIME TIMESTAMP NULL ,

Loading…
Cancel
Save