revert-70aa11f8
Dilshan Edirisuriya 9 years ago
commit c547d85f35

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

@ -18,7 +18,11 @@
*/
package org.wso2.carbon.device.mgt.common;
public class EnrolmentInfo {
import java.io.Serializable;
public class EnrolmentInfo implements Serializable{
private static final long serialVersionUID = 1998101712L;
public enum Status {
CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED

@ -0,0 +1,55 @@
/*
* Copyright (c) 2014, 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.device.mgt.common.configuration.mgt;
public class ConfigurationManagementException extends Exception {
private static final long serialVersionUID = -3151279311929070299L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ConfigurationManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public ConfigurationManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public ConfigurationManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public ConfigurationManagementException() {
super();
}
public ConfigurationManagementException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,45 @@
/*
* Copyright (c) 2014, 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.device.mgt.common.configuration.mgt;
/**
* This represents the tenant configuration management functionality which should be implemented by
* the device type plugins.
*/
public interface TenantConfigurationManagementService {
/**
* Method to add a operation to a device or a set of devices.
*
* @param tenantConfiguration Operation to be added.
* @param resourcePath Registry resource path.
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the
* configuration.
*/
public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws ConfigurationManagementException;
/**
* Method to retrieve the list of general tenant configurations.
*
* @param resourcePath Registry resource path.
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the
* operation list.
*/
public TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException;
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014, 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.device.mgt.core.config;
/**
* This class holds the constants used throughout the configuration manager.
*/
public class ConfigurationManagerConstants {
public static final class ContentTypes {
private ContentTypes() {
throw new AssertionError();
}
public static final String CONTENT_TYPE_ANY = "*/*";
public static final String MEDIA_TYPE_XML = "application/xml";
}
public static final class CharSets {
private CharSets() {
throw new AssertionError();
}
public static final String CHARSET_UTF8 = "UTF8";
}
}

@ -0,0 +1,97 @@
/*
* Copyright (c) 2014, 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.device.mgt.core.config.tenant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.core.config.ConfigurationManagerConstants;
import org.wso2.carbon.device.mgt.core.config.util.ConfigurationManagerUtil;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.api.RegistryException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
/**
* This class implements all the functionality exposed as part of the TenantConfigurationManagementService. Main usage of
* this module is, saving/retrieving tenant configurations to the registry.
*/
public class TenantConfigurationManagementServiceImpl
implements TenantConfigurationManagementService {
private static final Log log = LogFactory.getLog(TenantConfigurationManagementServiceImpl.class);
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath)
throws ConfigurationManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Persisting tenant configurations in Registry");
}
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(tenantConfiguration, writer);
Resource resource = ConfigurationManagerUtil.getConfigurationRegistry().newResource();
resource.setContent(writer.toString());
resource.setMediaType(ConfigurationManagerConstants.ContentTypes.MEDIA_TYPE_XML);
ConfigurationManagerUtil.putRegistryResource(resourcePath, resource);
status = true;
} catch (RegistryException e) {
throw new ConfigurationManagementException(
"Error occurred while persisting the Registry resource of Tenant Configuration : " + e.getMessage(), e);
} catch (JAXBException e) {
throw new ConfigurationManagementException(
"Error occurred while parsing the Tenant configuration : " + e.getMessage(), e);
}
return status;
}
@Override
public TenantConfiguration getConfiguration(String resourcePath)
throws ConfigurationManagementException {
Resource resource;
try {
resource = ConfigurationManagerUtil.getRegistryResource(resourcePath);
if(resource != null){
JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (TenantConfiguration) unmarshaller.unmarshal(
new StringReader(new String((byte[]) resource.getContent(), Charset
.forName(ConfigurationManagerConstants.CharSets.CHARSET_UTF8))));
}
return new TenantConfiguration();
} catch (JAXBException e) {
throw new ConfigurationManagementException(
"Error occurred while parsing the Tenant configuration : " + e.getMessage(), e);
} catch (RegistryException e) {
throw new ConfigurationManagementException(
"Error occurred while retrieving the Registry resource of Tenant Configuration : " + e.getMessage(), e);
}
}
}

@ -0,0 +1,70 @@
/*
* Copyright (c) 2014, 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.device.mgt.core.config.util;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.Registry;
public class ConfigurationManagerUtil {
public static Registry getConfigurationRegistry() throws ConfigurationManagementException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
return DeviceManagementDataHolder.getInstance().getRegistryService()
.getConfigSystemRegistry(
tenantId);
} catch (RegistryException e) {
throw new ConfigurationManagementException(
"Error in retrieving governance registry instance: " +
e.getMessage(), e);
}
}
public static Resource getRegistryResource(String path) throws ConfigurationManagementException {
try {
if(ConfigurationManagerUtil.getConfigurationRegistry().resourceExists(path)){
return ConfigurationManagerUtil.getConfigurationRegistry().get(path);
}
return null;
} catch (RegistryException e) {
throw new ConfigurationManagementException("Error in retrieving registry resource : " +
e.getMessage(), e);
}
}
public static boolean putRegistryResource(String path,
Resource resource)
throws ConfigurationManagementException {
boolean status;
try {
ConfigurationManagerUtil.getConfigurationRegistry().beginTransaction();
ConfigurationManagerUtil.getConfigurationRegistry().put(path, resource);
ConfigurationManagerUtil.getConfigurationRegistry().commitTransaction();
status = true;
} catch (RegistryException e) {
throw new ConfigurationManagementException(
"Error occurred while persisting registry resource : " +
e.getMessage(), e);
}
return status;
}
}

@ -179,7 +179,7 @@ public class DeviceDAOImpl implements DeviceDAO {
String sql =
"SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " +
"e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME " +
"FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME " +
"AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " +
"AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);

@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
@ -36,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfiguration
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
@ -171,6 +173,11 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider);
bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null);
/* Registering Tenant Configuration Management Service */
TenantConfigurationManagementService
tenantConfiguration = new TenantConfigurationManagementServiceImpl();
bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null);
/* Registering App Management service */
try {
AppManagementConfigurationManager.getInstance().initConfig();

@ -492,10 +492,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
DeviceManagementDAOFactory.openConnection();
device = deviceDAO.getDevice(deviceId, this.getTenantId());
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementException("Error occurred while obtaining the device for id " +
"'" + deviceId.getId() + "'", e);
} catch (SQLException e) {
throw new DeviceManagementException("Error occurred while obtaining the device for id " +
"'" + deviceId.getId() + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}

@ -42,6 +42,8 @@ public class Policy implements Comparable<Policy>, Serializable {
private String ownershipType; // Ownership type (COPE, BYOD, CPE)
private List<Device> devices; // Individual devices this policy should be applied
private List<String> users;
private boolean active;
private boolean updated;
/* Compliance data*/
@ -53,19 +55,6 @@ public class Policy implements Comparable<Policy>, Serializable {
private List<PolicyCriterion> policyCriterias;
/*These are related to time based policies*/
// private int startTime; // Start time to apply the policy.
// private int endTime; // After this time policy will not be applied
// private Date startDate; // Start date to apply the policy
// private Date endDate; // After this date policy will not be applied.
/*These are related to location based policies*/
// private String latitude; // Latitude
// private String longitude; // Longitude
//
private int tenantId;
private int profileId;
@ -163,6 +152,24 @@ public class Policy implements Comparable<Policy>, Serializable {
this.users = users;
}
@XmlElement
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@XmlElement
public boolean isUpdated() {
return updated;
}
public void setUpdated(boolean updated) {
this.updated = updated;
}
@XmlElement
public List<PolicyCriterion> getPolicyCriterias() {
return policyCriterias;
@ -172,6 +179,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.policyCriterias = policyCriterias;
}
@XmlElement
public String getCompliance() {
return Compliance;
}
@ -180,59 +188,6 @@ public class Policy implements Comparable<Policy>, Serializable {
Compliance = compliance;
}
// public int getStartTime() {
// return startTime;
// }
//
// public void setStartTime(int startTime) {
// this.startTime = startTime;
// }
//
// @XmlElement
// public int getEndTime() {
// return endTime;
// }
//
// public void setEndTime(int endTime) {
// this.endTime = endTime;
// }
//
// @XmlElement
// public Date getStartDate() {
// return startDate;
// }
//
// public void setStartDate(Date startDate) {
// this.startDate = startDate;
// }
//
// @XmlElement
// public Date getEndDate() {
// return endDate;
// }
//
// public void setEndDate(Date endDate) {
// this.endDate = endDate;
// }
//
// @XmlElement
// public String getLatitude() {
// return latitude;
// }
//
// public void setLatitude(String latitude) {
// this.latitude = latitude;
// }
//
// @XmlElement
// public String getLongitude() {
// return longitude;
// }
//
// public void setLongitude(String longitude) {
// this.longitude = longitude;
// }
@XmlElement
public Map<String, Object> getAttributes() {
return attributes;
@ -252,18 +207,6 @@ public class Policy implements Comparable<Policy>, Serializable {
}
/* static final Comparator<Policy> PRIORITY_ORDER =
new Comparator<Policy>() {
public int compare(Policy p1, Policy p2) {
int dateCmp = new Integer(p2.getId()).compareTo(new Integer(p1.getId()));
if (dateCmp != 0)
return dateCmp;
return (p1.getId() < p2.getId() ? -1 :
(p1.getId() == p2.getId() ? 0 : 1));
}
};*/
@Override
public int compareTo(Policy o) {
if (this.priorityId == o.priorityId)

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

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

@ -144,6 +144,15 @@
<artifactId>org.wso2.carbon.ntask.core</artifactId>
</dependency>
<!-- Registry dependencies-->
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<!-- Policy Management Dependencies-->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>

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

@ -144,13 +144,14 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET PRIORITY = ? WHERE ID = ? AND TENANT_ID = ?";
String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
for (Policy policy : policies) {
stmt.setInt(1, policy.getPriorityId());
stmt.setInt(2, policy.getId());
stmt.setInt(3, tenantId);
stmt.setInt(2, 1);
stmt.setInt(3, policy.getId());
stmt.setInt(4, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
@ -162,6 +163,137 @@ public class PolicyDAOImpl implements PolicyDAO {
return true;
}
@Override
public void activatePolicy(int policyId) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, 1);
stmt.setInt(2, 1);
stmt.setInt(3, policyId);
stmt.setInt(4, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId +
") in database", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void activatePolicies(List<Integer> policyIds) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
for (int policyId : policyIds) {
stmt.setInt(1, 1);
stmt.setInt(2, 1);
stmt.setInt(3, policyId);
stmt.setInt(4, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void markPoliciesAsUpdated(List<Integer> policyIds) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET UPDATED = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
for (int policyId : policyIds) {
stmt.setInt(1, 0);
stmt.setInt(2, policyId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void inactivatePolicy(int policyId) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET ACTIVE = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, 0);
stmt.setInt(2, 1);
stmt.setInt(3, policyId);
stmt.setInt(4, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId +
") in database", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public HashMap<Integer, Integer> getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
HashMap<Integer, Integer> map = new HashMap<>();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ?";
stmt.setInt(1, tenantId);
stmt = conn.prepareStatement(query);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
map.put(resultSet.getInt("POLICY_ID"), resultSet.getInt("DEVICE_TYPE_ID"));
}
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while reading the changed policies form database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return map;
}
@Override
public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException {
@ -477,15 +609,16 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "UPDATE DM_POLICY SET NAME= ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?" +
" WHERE ID = ? AND TENANT_ID = ?";
String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," +
" UPDATED = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, policy.getPolicyName());
stmt.setInt(2, policy.getProfile().getProfileId());
stmt.setInt(3, policy.getPriorityId());
stmt.setString(4, policy.getCompliance());
stmt.setInt(5, policy.getId());
stmt.setInt(6, tenantId);
stmt.setInt(5, 1);
stmt.setInt(6, policy.getId());
stmt.setInt(7, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
@ -497,6 +630,77 @@ public class PolicyDAOImpl implements PolicyDAO {
return policy;
}
@Override
public void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, policy.getId());
stmt.setInt(2, policy.getProfile().getDeviceType().getId());
stmt.setInt(3, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database for" +
" " +
"policy name (" + policy.getPolicyName() + ")", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void recordUpdatedPolicies(List<Policy> policies) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query);
for (Policy policy : policies) {
stmt.setInt(1, policy.getId());
stmt.setInt(2, policy.getProfile().getDeviceType().getId());
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "DELETE FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ? ";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while deleting the policy changes in the database for" +
" " +
"tenant id (" + tenantId + ")", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public Policy getPolicy(int policyId) throws PolicyManagerDAOException {
Connection conn;
@ -585,6 +789,8 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policies.add(policy);
}
return policies;
@ -884,12 +1090,16 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt = conn.prepareStatement(query);
stmt.setInt(1, policyId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
int deleted = stmt.executeUpdate();
if (log.isDebugEnabled()) {
log.debug("Policy (" + policyId + ") delete from database.");
}
if (deleted > 0) {
return true;
} else {
return false;
}
} catch (SQLException e) {
throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e);
} finally {
@ -948,8 +1158,9 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE)" +
" VALUES (?, ?, ?, ?, ?, ?)";
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
" " +
"UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, policy.getPolicyName());
@ -958,6 +1169,8 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(4, readHighestPriorityOfPolicies());
stmt.setString(5, policy.getCompliance());
stmt.setString(6, policy.getOwnershipType());
stmt.setInt(7, 0);
stmt.setInt(8, 0);
int affectedRows = stmt.executeUpdate();
@ -1183,4 +1396,31 @@ public class PolicyDAOImpl implements PolicyDAO {
return devicePolicyIds;
}
@Override
public HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
HashMap<Integer, Integer> devicePolicyIds = new HashMap<>();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
devicePolicyIds.put(resultSet.getInt("DEVICE_ID"), resultSet.getInt("POLICY_ID"));
}
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return devicePolicyIds;
}
}

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

@ -0,0 +1,94 @@
/*
* 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.enforcement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ntask.core.Task;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DelegationTask implements Task {
private static final Log log = LogFactory.getLog(DelegationTask.class);
@Override
public void setProperties(Map<String, String> map) {
}
@Override
public void init() {
}
@Override
public void execute() {
try {
PolicyManager policyManager = new PolicyManagerImpl();
List<DeviceType> deviceTypes = policyManager.applyChangesMadeToPolicies();
if (log.isDebugEnabled()) {
log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size());
}
if (!deviceTypes.isEmpty()) {
DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance()
.getDeviceManagementService();
List<Device> devices = new ArrayList<>();
for (DeviceType deviceType : deviceTypes) {
try {
devices.addAll(service.getAllDevices(deviceType.getName()));
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while taking the devices", e);
}
}
HashMap<Integer, Integer> deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds();
List<Device> toBeNotified = new ArrayList<>();
for (Device device : devices) {
if (deviceIdPolicy.containsKey(device.getId())) {
toBeNotified.add(device);
}
}
if (!toBeNotified.isEmpty()) {
PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified);
enforcementDelegator.delegate();
}
}
} catch (PolicyManagementException e) {
log.error("Error occurred while getting the policies applied to devices.", e);
} catch (PolicyDelegationException e) {
log.error("Error occurred while running the delegation task.", e);
}
}
}

@ -18,7 +18,6 @@
*/
package org.wso2.carbon.policy.mgt.core.enforcement;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Policy;
@ -26,6 +25,10 @@ import java.util.List;
public interface PolicyEnforcementDelegator {
void delegate(Policy policy, List<Device> devices) throws PolicyDelegationException;
void delegate() throws PolicyDelegationException;
Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException;
void addPolicyOperation(List<DeviceIdentifier> deviceIdentifiers, Policy policy) throws PolicyDelegationException;
}

@ -18,33 +18,93 @@
*/
package org.wso2.carbon.policy.mgt.core.enforcement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.util.ArrayList;
import java.util.List;
public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator {
public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator{
private OperationManager operationManager = new OperationManagerImpl();
private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class);
private List<Device> devices;
public PolicyEnforcementDelegatorImpl(List<Device> devices) {
log.info("Policy re-enforcing stared due to change of the policies.");
if (log.isDebugEnabled()) {
for (Device device : devices) {
log.debug("Policy re-enforcing for device :" + device.getDeviceIdentifier() + " - Type : "
+ device.getType());
}
}
this.devices = devices;
}
@Override
public void delegate(Policy policy, List<Device> devices) throws PolicyDelegationException {
try {
List<DeviceIdentifier> deviceIds = new ArrayList<>();
public void delegate() throws PolicyDelegationException {
for (Device device : devices) {
deviceIds.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(device.getDeviceIdentifier());
identifier.setType(device.getType());
Policy policy = this.getEffectivePolicy(identifier);
if (policy != null) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(identifier);
this.addPolicyOperation(deviceIdentifiers, policy);
}
operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIds);
}
}
@Override
public Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException {
try {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
return policyManagerService.getPEP().getEffectivePolicy(identifier);
//return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier);
} catch (PolicyEvaluationException e) {
String msg = "Error occurred while retrieving the effective policy for devices.";
log.error(msg, e);
throw new PolicyDelegationException(msg, e);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving the effective policy for devices.";
log.error(msg, e);
throw new PolicyDelegationException(msg, e);
}
}
@Override
public void addPolicyOperation(List<DeviceIdentifier> deviceIdentifiers, Policy policy) throws
PolicyDelegationException {
try {
OperationManager operationManager = new OperationManagerImpl();
operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers);
} catch (OperationManagementException e) {
throw new PolicyDelegationException("Error occurred while delegating policy information to " +
"the respective enforcement points", e);
String msg = "Error occurred while adding the operation to device.";
log.error(msg, e);
throw new PolicyDelegationException(msg, e);
}
}
}

@ -166,10 +166,8 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint {
}
} catch (OperationManagementException e) {
String msg = "Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType();
log.error(msg, e);
throw new PolicyComplianceException(msg, e);
throw new PolicyComplianceException("Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " +
deviceIdentifier.getType(), e);
}
}

@ -20,24 +20,25 @@ package org.wso2.carbon.policy.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
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.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileManagementException;
import org.wso2.carbon.policy.mgt.core.enforcement.PolicyDelegationException;
import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegator;
import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegatorImpl;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.TaskInfo;
import org.wso2.carbon.ntask.core.TaskManager;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
@ -46,13 +47,13 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
private PolicyManager policyManager;
private ProfileManager profileManager;
private FeatureManager featureManager;
private PolicyEnforcementDelegator delegator;
// private PolicyEnforcementDelegator delegator;
public PolicyAdministratorPointImpl() {
this.policyManager = new PolicyManagerImpl();
this.profileManager = new ProfileManagerImpl();
this.featureManager = new FeatureManagerImpl();
this.delegator = new PolicyEnforcementDelegatorImpl();
// this.delegator = new PolicyEnforcementDelegatorImpl();
}
@Override
@ -82,6 +83,16 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
return policyManager.updatePolicyPriorities(policies);
}
@Override
public void activatePolicy(int policyId) throws PolicyManagementException {
policyManager.activatePolicy(policyId);
}
@Override
public void inactivatePolicy(int policyId) throws PolicyManagementException {
policyManager.inactivatePolicy(policyId);
}
@Override
public boolean deletePolicy(Policy policy) throws PolicyManagementException {
return policyManager.deletePolicy(policy);
@ -93,7 +104,82 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
}
@Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, Policy policy) throws PolicyManagementException {
public void publishChanges() throws PolicyManagementException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
taskService.registerTaskType(PolicyManagementConstants.DELEGATION_TASK_TYPE);
if (log.isDebugEnabled()) {
log.debug("Policy delegations task is started for the tenant id " + tenantId);
}
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.DELEGATION_TASK_TYPE);
TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo();
triggerInfo.setIntervalMillis(0);
triggerInfo.setRepeatCount(1);
Map<String, String> properties = new HashMap<>();
properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId));
String taskName = PolicyManagementConstants.DELEGATION_TASK_NAME + "_" + String.valueOf(tenantId);
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.DELEGATION_TASK_CLAZZ, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} catch (TaskException e) {
String msg = "Error occurred while creating the policy delegation task for tenant " + PrivilegedCarbonContext.
getThreadLocalCarbonContext().getTenantId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
// List<DeviceType> deviceTypes = policyManager.applyChangesMadeToPolicies();
//
// if(log.isDebugEnabled()) {
// log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() );
// }
//
// if (!deviceTypes.isEmpty()) {
//
//
// DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance()
// .getDeviceManagementService();
// List<Device> devices = new ArrayList<>();
// for (DeviceType deviceType : deviceTypes) {
// try {
// devices.addAll(service.getAllDevices(deviceType.getName()));
// } catch (DeviceManagementException e) {
// throw new PolicyManagementException("Error occurred while taking the devices", e);
// }
// }
// HashMap<Integer, Integer> deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds();
// List<Device> toBeNotified = new ArrayList<>();
//
// for (Device device : devices) {
// if (deviceIdPolicy.containsKey(device.getId())) {
// toBeNotified.add(device);
// }
// }
// if (!toBeNotified.isEmpty()) {
//
// // ExecutorService executorService = getExecutor();
// // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified);
//// Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified));
//// thread.start();
// }
// }
}
@Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, Policy policy) throws
PolicyManagementException {
return policyManager.addPolicyToDevice(deviceIdentifierList, policy);
}
@ -185,7 +271,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
try {
return profileManager.getProfile(profileId);
} catch (ProfileManagementException e) {
String msg = "Error occurred while retriving profile";
String msg = "Error occurred while retrieving profile";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}

@ -32,14 +32,56 @@ public class PolicyFilterImpl implements PolicyFilter {
private static final Log log = LogFactory.getLog(PolicyFilterImpl.class);
@Override
public List<Policy> filterActivePolicies(List<Policy> policies) {
if (log.isDebugEnabled()) {
log.debug("No of policies went in to filterActivePolicies : " + policies.size());
for (Policy policy : policies) {
log.debug("Names of policy went in to filterActivePolicies : " + policy.getPolicyName());
}
}
List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) {
if (policy.isActive()) {
temp.add(policy);
}
}
if (log.isDebugEnabled()) {
log.debug("No of policies returned from filterActivePolicies :" + policies.size());
for (Policy policy : temp) {
log.debug("Names of policy filtered in filterActivePolicies : " + policy.getPolicyName());
}
}
return temp;
}
@Override
public List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies) {
if (log.isDebugEnabled()) {
log.debug("No of policies went in to filterRolesBasedPolicies : " + policies.size());
for (Policy policy : policies) {
log.debug("Names of policy went in to filterRolesBasedPolicies : " + policy.getPolicyName());
}
log.debug("Roles passed to match.");
for(String role : roles){
log.debug("Role name passed : " + role);
}
}
List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) {
List<String> tempRoles = policy.getRoles();
if (tempRoles.isEmpty()) {
if(log.isDebugEnabled()) {
log.debug("Roles list is empty.");
}
temp.add(policy);
continue;
}
@ -57,12 +99,28 @@ public class PolicyFilterImpl implements PolicyFilter {
}
}
}
if (log.isDebugEnabled()) {
log.debug("No of policies returned from filterRolesBasedPolicies : " + policies.size());
for (Policy policy : temp) {
log.debug("Names of policy filtered in filterRolesBasedPolicies : " + policy.getPolicyName());
}
}
return temp;
}
@Override
public List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> policies) {
if (log.isDebugEnabled()) {
log.debug("No of policies went in to filterOwnershipTypeBasedPolicies : " + policies.size());
log.debug("Ownership type : " + ownershipType);
for (Policy policy : policies) {
log.debug("Names of policy went in to filterOwnershipTypeBasedPolicies : " + policy.getPolicyName());
}
}
List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) {
if (ownershipType.equalsIgnoreCase(policy.getOwnershipType()) ||
@ -70,22 +128,56 @@ public class PolicyFilterImpl implements PolicyFilter {
temp.add(policy);
}
}
if (log.isDebugEnabled()) {
log.debug("No of policies returned from filterOwnershipTypeBasedPolicies : " + policies.size());
for (Policy policy : temp) {
log.debug("Names of policy filtered in filterOwnershipTypeBasedPolicies : " + policy.getPolicyName());
}
}
return temp;
}
@Override
public List<Policy> filterDeviceTypeBasedPolicies(String deviceType, List<Policy> policies) {
if (log.isDebugEnabled()) {
log.debug("No of policies went in to filterDeviceTypeBasedPolicies : " + policies.size());
log.debug("Device type : " + deviceType);
for (Policy policy : policies) {
log.debug("Names of policy went in to filterDeviceTypeBasedPolicies : " + policy.getPolicyName());
}
}
List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) {
if (deviceType.equalsIgnoreCase(policy.getProfile().getDeviceType().getName())) {
temp.add(policy);
}
}
if (log.isDebugEnabled()) {
log.debug("No of policies returned from filterDeviceTypeBasedPolicies : " + policies.size());
for (Policy policy : temp) {
log.debug("Names of policy filtered in filterDeviceTypeBasedPolicies : " + policy.getPolicyName());
}
}
return temp;
}
@Override
public List<Policy> filterUserBasedPolicies(String username, List<Policy> policies) {
if (log.isDebugEnabled()) {
log.debug("No of policies went in to filterUserBasedPolicies : " + policies.size());
log.debug("User name : " + username);
for (Policy policy : policies) {
log.debug("Names of policy went in to filterUserBasedPolicies : " + policy.getPolicyName());
}
}
List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) {
@ -106,6 +198,14 @@ public class PolicyFilterImpl implements PolicyFilter {
}
}
}
if (log.isDebugEnabled()) {
log.debug("No of policies returned from filterUserBasedPolicies : " + policies.size());
for (Policy policy : temp) {
log.debug("Names of policy filtered in filterUserBasedPolicies : " + policy.getPolicyName());
}
}
return temp;
}
}

@ -27,13 +27,16 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import java.util.ArrayList;
import java.util.HashMap;
@ -58,14 +61,17 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
@Override
public PIPDevice getDeviceData(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
PIPDevice pipDevice = new PIPDevice();
org.wso2.carbon.device.mgt.common.Device device;
Device device;
DeviceType deviceType = new DeviceType();
deviceType.setName(deviceIdentifier.getType());
deviceManagementService = getDeviceManagementService();
DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl();
try {
device = deviceManagementService.getDevice(deviceIdentifier);
Thread.currentThread();
if (device != null) {
/*deviceManagementService.getDeviceType(deviceIdentifier.getType());*/
pipDevice.setDevice(device);
pipDevice.setRoles(getRoleOfDevice(device));
@ -78,6 +84,13 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
// pipDevice.setLongitude();
// pipDevice.setAltitude();
// pipDevice.setTimestamp();
} else {
// Remove this
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
log.debug("StackTraceElement : " + ste);
}
throw new PolicyManagementException("Device details cannot be null.");
}
} catch (DeviceManagementException e) {
String msg = "Error occurred when retrieving the data related to device from the database.";
log.error(msg, e);
@ -93,6 +106,16 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
List<Policy> policies = policyManager.getPoliciesOfDeviceType(pipDevice.getDeviceType().getName());
PolicyFilter policyFilter = new PolicyFilterImpl();
if (log.isDebugEnabled()) {
log.debug("No of policies for the device type : " + pipDevice.getDeviceType().getName() + " : " +
policies.size());
for (Policy policy : policies) {
log.debug("Names of policy for above device type : " + policy.getPolicyName());
}
}
policies = policyFilter.filterActivePolicies(policies);
if (pipDevice.getDeviceType() != null) {
policies = policyFilter.filterDeviceTypeBasedPolicies(pipDevice.getDeviceType().getName(), policies);
}
@ -102,10 +125,18 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
if (pipDevice.getRoles() != null) {
policies = policyFilter.filterRolesBasedPolicies(pipDevice.getRoles(), policies);
}
if(pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) {
if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) {
policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies);
}
if (log.isDebugEnabled()) {
log.debug("No of policies selected for the device type : " + pipDevice.getDeviceType().getName() + " : " +
policies.size());
for (Policy policy : policies) {
log.debug("Names of selected policy for above device type : " + policy.getPolicyName());
}
}
return policies;
}
@ -117,12 +148,14 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
private String[] getRoleOfDevice(Device device) throws PolicyManagementException {
try {
return CarbonContext.getThreadLocalCarbonContext().getUserRealm().
getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner());
UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
if (userRealm != null) {
return userRealm.getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner());
} else {
return null;
}
} catch (UserStoreException e) {
String msg = "Error occurred when retrieving roles related to user name.";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
throw new PolicyManagementException("Error occurred when retrieving roles related to user name.", e);
}
}
@ -139,12 +172,11 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
}
}
}
return finalPolicies;
}
private DeviceManagementProviderService getDeviceManagementService() {
return PolicyManagementDataHolder.getInstance().getDeviceManagementService();
return new DeviceManagementProviderServiceImpl();
}
}

@ -31,6 +31,8 @@ import org.wso2.carbon.policy.mgt.core.config.PolicyConfigurationManager;
import org.wso2.carbon.policy.mgt.core.config.PolicyManagementConfig;
import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl;
import org.wso2.carbon.user.core.service.RealmService;
/**
@ -82,6 +84,9 @@ public class PolicyManagementServiceComponent {
componentContext.getBundleContext().registerService(
PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null);
TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl();
taskScheduleService.startTask(30000);
} catch (Throwable t) {
log.error("Error occurred while initializing the Policy management core.", t);
}

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

@ -21,39 +21,35 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.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.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint;
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.Policy;
import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.dao.*;
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.sql.SQLException;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MonitoringManagerImpl implements MonitoringManager {
@ -81,8 +77,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
PolicyManager manager = new PolicyManagerImpl();
Device device = service.getDevice(deviceIdentifier);
Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); //policyDAO.getAppliedPolicy(device
// .getId());
Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier);
if (policy != null) {
PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance().
getPolicyMonitoringService(deviceIdentifier.getType());
@ -110,14 +105,19 @@ public class MonitoringManagerImpl implements MonitoringManager {
//This was added because update query below that did not return the update table primary key.
if (complianceFeatures != null && !complianceFeatures.isEmpty()) {
try {
PolicyManagementDAOFactory.beginTransaction();
monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId());
if (log.isDebugEnabled()) {
log.debug("Compliance status primary key " + complianceData.getId());
}
// complianceData.setId(cmf.getId());
monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures);
monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(),
complianceFeatures);
PolicyManagementDAOFactory.commitTransaction();
} finally {
PolicyManagementDAOFactory.closeConnection();
}
complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData);
List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList();
for (ComplianceFeature compFeature : complianceFeatures) {
@ -128,11 +128,14 @@ public class MonitoringManagerImpl implements MonitoringManager {
}
}
} else {
try {
PolicyManagementDAOFactory.beginTransaction();
monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId());
//complianceData.setId(cmf.getId());
monitoringDAO.deleteNoneComplianceData(complianceData.getId());
PolicyManagementDAOFactory.commitTransaction();
} finally {
PolicyManagementDAOFactory.closeConnection();
}
}
} else {
if (log.isDebugEnabled()) {
@ -151,8 +154,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException("Unable to add the none compliance features to database for device " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
return complianceFeatures;
}
@ -162,7 +163,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
//deviceDAO.getDevice(deviceIdentifier, tenantId);
PolicyManagementDAOFactory.openConnection();
ComplianceData complianceData = monitoringDAO.getCompliance(device.getId());
if (complianceData == null || !complianceData.isStatus()) {
@ -214,19 +214,30 @@ public class MonitoringManagerImpl implements MonitoringManager {
@Override
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException {
try {
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
//int tenantId = PolicyManagerUtil.getTenantId();
Map<Integer, Device> deviceIds = new HashMap<>();
List<ComplianceData> complianceDatas;
HashMap<Integer, Integer> devicePolicyIdMap;
for (Device device : devices) {
deviceIds.put(device.getId(), device);
}
List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet());
List<ComplianceData> complianceDatas = monitoringDAO.getCompliance(deviceIDs);
HashMap<Integer, Integer> devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs);
try {
PolicyManagementDAOFactory.openConnection();
complianceDatas = monitoringDAO.getCompliance(deviceIDs);
devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs);
} catch (SQLException e) {
throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
} catch (MonitoringDAOException e) {
throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
} catch (PolicyManagerDAOException e) {
throw new PolicyComplianceException("SQL error occurred while getting policy details.", e);
}
Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
@ -235,7 +246,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
Map<Integer, ComplianceData> tempMap = new HashMap<>();
try {
if (complianceDatas != null || !complianceDatas.isEmpty()) {
for (ComplianceData complianceData : complianceDatas) {
@ -256,7 +267,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
}
for (Device device : devices) {
if (!tempMap.containsKey(device.getId())) {
if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) {
deviceIdsToAddOperation.put(device.getId(), device);
firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
}
@ -272,7 +283,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.beginTransaction();
if (!deviceIdsToAddOperation.isEmpty()) {
this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values()));
monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
}
@ -282,20 +292,26 @@ public class MonitoringManagerImpl implements MonitoringManager {
// decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices(
// new ArrayList<>(deviceIdsWithExistingOperation.values())));
}
PolicyManagementDAOFactory.commitTransaction();
} catch (MonitoringDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException("Error occurred from monitoring dao.", e);
} catch (OperationManagementException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e);
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException("Error occurred reading the applied policies to devices.", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
if (!deviceIdsToAddOperation.isEmpty()) {
try {
this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values()));
} catch (OperationManagementException e) {
throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e);
}
}
}
private void addMonitoringOperationsToDatabase(List<Device> devices)

@ -20,34 +20,29 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.logging.Log;
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.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.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.dao.*;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.*;
public class PolicyManagerImpl implements PolicyManager {
private PolicyDAO policyDAO;
private ProfileDAO profileDAO;
private FeatureDAO featureDAO;
private DeviceDAO deviceDAO;
// private DeviceTypeDAO deviceTypeDAO;
private ProfileManager profileManager;
private static Log log = LogFactory.getLog(PolicyManagerImpl.class);
@ -55,8 +50,6 @@ public class PolicyManagerImpl implements PolicyManager {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
this.profileDAO = PolicyManagementDAOFactory.getProfileDAO();
this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
// this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.profileManager = new ProfileManagerImpl();
}
@ -72,7 +65,6 @@ public class PolicyManagerImpl implements PolicyManager {
profile.setCreatedDate(currentTimestamp);
profile.setUpdatedDate(currentTimestamp);
profileDAO.addProfile(profile);
featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId());
}
@ -110,17 +102,6 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias());
}
// if (policy.getEndDate() != null & policy.getStartDate() != null) {
// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy);
// }
//
// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) {
// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy);
// }
//
// if (policy.getLatitude() != null && policy.getLongitude() != null) {
// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy);
// }
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
@ -147,7 +128,13 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.beginTransaction();
policy = policyDAO.updatePolicy(policy);
// This will keep track of the policies updated.
policyDAO.recordUpdatedPolicy(policy);
policyDAO.updatePolicy(policy);
profileDAO.updateProfile(policy.getProfile());
featureDAO.updateProfileFeatures(policy.getProfile().getProfileFeaturesList(), policy.getProfile()
.getProfileId());
policyDAO.deleteAllPolicyRelatedConfigs(policy.getId());
if (policy.getUsers() != null) {
@ -177,23 +164,20 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias());
}
// if (policy.getEndDate() != null & policy.getStartDate() != null) {
// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy);
// }
//
// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) {
// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy);
// }
//
// if (policy.getLatitude() != null && policy.getLongitude() != null) {
// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy);
// }
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while updating the policy ("
+ policy.getId() + " - " + policy.getPolicyName() + ")", e);
} catch (ProfileManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while updating the profile (" +
policy.getProfile().getProfileName() + ")", e);
} catch (FeatureManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while updating the profile features (" +
policy.getProfile().getProfileName() + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -206,6 +190,7 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.beginTransaction();
bool = policyDAO.updatePolicyPriorities(policies);
policyDAO.recordUpdatedPolicies(policies);
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
@ -245,12 +230,13 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public boolean deletePolicy(int policyId) throws PolicyManagementException {
boolean bool;
try {
PolicyManagementDAOFactory.beginTransaction();
Policy policy = policyDAO.getPolicy(policyId);
policyDAO.deleteAllPolicyRelatedConfigs(policyId);
policyDAO.deletePolicy(policyId);
bool = policyDAO.deletePolicy(policyId);
if (log.isDebugEnabled()) {
log.debug("Profile ID: " + policy.getProfileId());
@ -260,7 +246,7 @@ public class PolicyManagerImpl implements PolicyManager {
profileDAO.deleteProfile(policy.getProfileId());
PolicyManagementDAOFactory.commitTransaction();
return true;
return bool;
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while deleting the policy (" + policyId + ")", e);
@ -278,18 +264,56 @@ public class PolicyManagerImpl implements PolicyManager {
}
@Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList,
Policy policy) throws PolicyManagementException {
public void activatePolicy(int policyId) throws PolicyManagementException {
try {
Policy policy = this.getPolicy(policyId);
PolicyManagementDAOFactory.beginTransaction();
if (policy.getId() == 0) {
policyDAO.addPolicy(policy);
policyDAO.activatePolicy(policyId);
policyDAO.recordUpdatedPolicy(policy);
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while activating the policy. (Id : " + policyId + ")" +
"", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
}
@Override
public void inactivatePolicy(int policyId) throws PolicyManagementException {
try {
Policy policy = this.getPolicy(policyId);
PolicyManagementDAOFactory.beginTransaction();
policyDAO.inactivatePolicy(policyId);
policyDAO.recordUpdatedPolicy(policy);
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while inactivating the policy. (Id : " + policyId +
")" +
"", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
}
@Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList,
Policy policy) throws PolicyManagementException {
try {
List<Device> deviceList = new ArrayList<>();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) {
deviceList.add(service.getDevice(deviceIdentifier));
}
PolicyManagementDAOFactory.beginTransaction();
if (policy.getId() == 0) {
policyDAO.addPolicy(policy);
}
policy = policyDAO.addPolicyToDevice(deviceList, policy);
PolicyManagementDAOFactory.commitTransaction();
@ -391,17 +415,12 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.openConnection();
policy = policyDAO.getPolicyByProfileID(profileId);
deviceList = getPolicyAppliedDevicesIds(policy.getId());
roleNames = policyDAO.getPolicyAppliedRoles(policy.getId());
// policyDAO.getDatesOfPolicy(policy);
// policyDAO.getTimesOfPolicy(policy);
// policyDAO.getLocationsOfPolicy(policy);
roleNames = policyDAO.getPolicyAppliedRoles(policy.getId());
profile = profileDAO.getProfiles(profileId);
policy.setProfile(profile);
policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" +
@ -414,6 +433,10 @@ public class PolicyManagerImpl implements PolicyManager {
} finally {
PolicyManagementDAOFactory.closeConnection();
}
// This is due to connection close in following method too.
deviceList = getPolicyAppliedDevicesIds(policy.getId());
policy.setDevices(deviceList);
return policy;
}
@ -427,17 +450,13 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.openConnection();
policy = policyDAO.getPolicy(policyId);
deviceList = getPolicyAppliedDevicesIds(policyId);
roleNames = policyDAO.getPolicyAppliedRoles(policyId);
// policyDAO.getDatesOfPolicy(policy);
// policyDAO.getTimesOfPolicy(policy);
// policyDAO.getLocationsOfPolicy(policy);
roleNames = policyDAO.getPolicyAppliedRoles(policyId);
Profile profile = profileDAO.getProfiles(policy.getProfileId());
policy.setProfile(profile);
policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" +
@ -450,11 +469,16 @@ public class PolicyManagerImpl implements PolicyManager {
} finally {
PolicyManagementDAOFactory.closeConnection();
}
// This is done because connection close in below method too.
deviceList = this.getPolicyAppliedDevicesIds(policyId);
policy.setDevices(deviceList);
return policy;
}
@Override
public List<Policy> getPolicies() throws PolicyManagementException {
List<Policy> policyList;
List<Profile> profileList;
try {
@ -465,7 +489,6 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies();
// List<Profile> profileList = profileDAO.getAllProfiles();
for (Policy policy : policyList) {
for (Profile profile : profileList) {
@ -473,13 +496,9 @@ public class PolicyManagerImpl implements PolicyManager {
policy.setProfile(profile);
}
}
policy.setDevices(getPolicyAppliedDevicesIds(policy.getId()));
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
// policyDAO.getDatesOfPolicy(policy);
// policyDAO.getTimesOfPolicy(policy);
// policyDAO.getLocationsOfPolicy(policy);
}
Collections.sort(policyList);
} catch (PolicyManagerDAOException e) {
@ -489,6 +508,13 @@ public class PolicyManagerImpl implements PolicyManager {
} finally {
PolicyManagementDAOFactory.closeConnection();
}
// Following is done because connection close has been implemented in every method.
for (Policy policy : policyList) {
policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId()));
}
return policyList;
}
@ -498,9 +524,11 @@ public class PolicyManagerImpl implements PolicyManager {
List<Integer> policyIdList;
List<Policy> policies = new ArrayList<>();
try {
PolicyManagementDAOFactory.openConnection();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
PolicyManagementDAOFactory.openConnection();
policyIdList = policyDAO.getPolicyIdsOfDevice(device);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policies for device identifier (" +
@ -612,24 +640,45 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public List<Device> getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException {
List<Device> deviceList = new ArrayList<>();
List<Integer> deviceIds;
try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> allDevices = service.getAllDevices();
PolicyManagementDAOFactory.openConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
//int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId);
HashMap<Integer, Device> allDeviceMap = new HashMap<>();
if(!allDevices.isEmpty()) {
allDeviceMap = PolicyManagerUtil.covertDeviceListToMap(allDevices);
}
for (int deviceId : deviceIds) {
//TODO FIX ME
deviceList.add(deviceDAO.getDevice(new DeviceIdentifier(Integer.toString(deviceId), ""), tenantId));
if(allDeviceMap.containsKey(deviceId)){
if(log.isDebugEnabled()) {
log.debug("Policy Applied device ids .............: " + deviceId + " - Policy Id " + policyId);
}
deviceList.add(allDeviceMap.get(deviceId));
}
//TODO FIX ME -- This is wrong, Device id is not device identifier, so converting is wrong.
//deviceList.add(deviceDAO.getDevice(new DeviceIdentifier(Integer.toString(deviceId), ""), tenantId));
}
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the device ids related to policy id (" +
policyId + ")", e);
} catch (DeviceManagementDAOException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -665,6 +714,47 @@ public class PolicyManagerImpl implements PolicyManager {
}
}
@Override
public List<DeviceType> applyChangesMadeToPolicies() throws PolicyManagementException {
List<DeviceType> changedDeviceTypes = new ArrayList<>();
try {
//HashMap<Integer, Integer> map = policyDAO.getUpdatedPolicyIdandDeviceTypeId();
List<Policy> updatedPolicies = new ArrayList<>();
// List<Policy> activePolicies = new ArrayList<>();
// List<Policy> inactivePolicies = new ArrayList<>();
List<Integer> updatedPolicyIds = new ArrayList<>();
List<Policy> allPolicies = this.getPolicies();
for (Policy policy : allPolicies) {
if (policy.isUpdated()) {
updatedPolicies.add(policy);
updatedPolicyIds.add(policy.getId());
if (!changedDeviceTypes.contains(policy.getProfile().getDeviceType())) {
changedDeviceTypes.add(policy.getProfile().getDeviceType());
}
}
// if (policy.isActive()) {
// activePolicies.add(policy);
// } else {
// inactivePolicies.add(policy);
// }
}
PolicyManagementDAOFactory.beginTransaction();
policyDAO.markPoliciesAsUpdated(updatedPolicyIds);
policyDAO.removeRecordsAboutUpdatedPolicies();
PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
return changedDeviceTypes;
}
@Override
public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy)
throws PolicyManagementException {
@ -674,13 +764,11 @@ public class PolicyManagerImpl implements PolicyManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
deviceId = device.getId();
// boolean exist = policyDAO.checkPolicyAvailable(deviceId);
PolicyManagementDAOFactory.beginTransaction();
Policy policySaved = policyDAO.getAppliedPolicy(deviceId);
if (policySaved != null && policySaved.getId() != 0) {
if (policy.getId() != policySaved.getId()){
if (policy.getId() != policySaved.getId()) {
policyDAO.updateEffectivePolicyToDevice(deviceId, policy);
}
} else {
@ -705,9 +793,9 @@ public class PolicyManagerImpl implements PolicyManager {
boolean exist;
try {
PolicyManagementDAOFactory.openConnection();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
PolicyManagementDAOFactory.openConnection();
exist = policyDAO.checkPolicyAvailable(device.getId());
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while checking whether device has a policy " +
@ -726,9 +814,10 @@ public class PolicyManagerImpl implements PolicyManager {
@Override
public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
try {
PolicyManagementDAOFactory.openConnection();
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier);
PolicyManagementDAOFactory.openConnection();
policyDAO.setPolicyApplied(device.getId());
return true;
} catch (PolicyManagerDAOException e) {
@ -782,4 +871,18 @@ public class PolicyManagerImpl implements PolicyManager {
return policy;
}
@Override
public HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException {
try {
PolicyManagementDAOFactory.openConnection();
return policyDAO.getAppliedPolicyIdsDeviceIds();
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while reading the policy applied database.", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while reading the policy applied database.", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
}
}

@ -42,13 +42,13 @@ public class ProfileManagerImpl implements ProfileManager {
private static Log log = LogFactory.getLog(ProfileManagerImpl.class);
private ProfileDAO profileDAO;
private FeatureDAO featureDAO;
private DeviceDAO deviceDAO;
// private DeviceDAO deviceDAO;
private DeviceTypeDAO deviceTypeDAO;
public ProfileManagerImpl() {
profileDAO = PolicyManagementDAOFactory.getProfileDAO();
featureDAO = PolicyManagementDAOFactory.getFeatureDAO();
deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
// deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
}
@ -91,7 +91,7 @@ public class ProfileManagerImpl implements ProfileManager {
try {
PolicyManagementDAOFactory.beginTransaction();
profile = profileDAO.updateProfile(profile);
profileDAO.updateProfile(profile);
featureDAO.updateProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId());
PolicyManagementDAOFactory.commitTransaction();
} catch (ProfileManagerDAOException e) {
@ -149,35 +149,54 @@ public class ProfileManagerImpl implements ProfileManager {
PolicyManagementDAOFactory.openConnection();
profile = profileDAO.getProfiles(profileId);
featureList = featureDAO.getFeaturesForProfile(profileId);
deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId());
profile.setProfileFeaturesList(featureList);
profile.setDeviceType(deviceType);
} catch (ProfileManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting profile id (" + profileId + ")", e);
} catch (FeatureManagerDAOException e) {
throw new ProfileManagementException("Error occurred while getting features related profile id (" +
profileId + ")", e);
} catch (DeviceManagementDAOException e) {
throw new ProfileManagementException("Error occurred while getting device type related profile id (" +
profileId + ")", e);
} catch (SQLException e) {
throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
try {
DeviceManagementDAOFactory.openConnection();
deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId());
} catch (DeviceManagementDAOException e) {
throw new ProfileManagementException("Error occurred while getting features related profile id (" +
profileId + ")", e);
} catch (SQLException e) {
throw new ProfileManagementException("SQL exception occurred while getting features related profile id (" +
profileId + ")", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
profile.setDeviceType(deviceType);
return profile;
}
@Override
public List<Profile> getAllProfiles() throws ProfileManagementException {
List<Profile> profileList;
List<DeviceType> deviceTypes;
try {
try {
DeviceManagementDAOFactory.openConnection();
deviceTypes = deviceTypeDAO.getDeviceTypes();
} finally {
DeviceManagementDAOFactory.closeConnection();
}
PolicyManagementDAOFactory.openConnection();
profileList = profileDAO.getAllProfiles();
List<ProfileFeature> featureList = featureDAO.getAllProfileFeatures();
List<DeviceType> deviceTypes = deviceTypeDAO.getDeviceTypes();
for (Profile profile : profileList) {
List<ProfileFeature> list = new ArrayList<ProfileFeature>();
@ -204,6 +223,7 @@ public class ProfileManagerImpl implements ProfileManager {
throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
// DeviceManagementDAOFactory.closeConnection();
}
return profileList;
}
@ -212,9 +232,16 @@ public class ProfileManagerImpl implements ProfileManager {
public List<Profile> getProfilesOfDeviceType(String deviceTypeName) throws ProfileManagementException {
List<Profile> profileList;
List<ProfileFeature> featureList;
DeviceType deviceType;
try {
try {
DeviceManagementDAOFactory.openConnection();
deviceType = deviceTypeDAO.getDeviceType(deviceTypeName);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
PolicyManagementDAOFactory.openConnection();
DeviceType deviceType = deviceTypeDAO.getDeviceType(deviceTypeName);
profileList = profileDAO.getProfilesOfDeviceType(deviceType);
featureList = featureDAO.getAllProfileFeatures();
@ -238,6 +265,7 @@ public class ProfileManagerImpl implements ProfileManager {
throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
return profileList;
}

@ -23,6 +23,7 @@ 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.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -62,8 +63,19 @@ public class MonitoringTask implements Task {
log.debug("Monitoring task started to run.");
}
List<DeviceType> deviceTypes = new ArrayList<>();
try {
List<DeviceType> deviceTypes = deviceTypeDAO.getDeviceTypes();
DeviceManagementDAOFactory.openConnection();
deviceTypes = deviceTypeDAO.getDeviceTypes();
} catch (Exception e) {
log.error("Error occurred while getting the device types.", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
if (!deviceTypes.isEmpty()) {
try {
DeviceManagementProviderService deviceManagementProviderService =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
MonitoringManager monitoringManager = new MonitoringManagerImpl();
@ -102,8 +114,10 @@ public class MonitoringTask implements Task {
log.debug("Monitoring task running completed.");
}
} catch (Exception e) {
String msg = "Error occurred while trying to run a task.";
log.error(msg, e);
log.error("Error occurred while trying to run a task.", e);
}
} else {
log.info("No device types registered currently. So did not run the monitoring task.");
}
}

@ -29,7 +29,6 @@ import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
import java.util.HashMap;
@ -48,13 +47,13 @@ public class TaskScheduleServiceImpl implements TaskScheduleService {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
taskService.registerTaskType(PolicyManagementConstants.TASK_TYPE);
taskService.registerTaskType(PolicyManagementConstants.MONITORING_TASK_TYPE);
if (log.isDebugEnabled()) {
log.debug("Monitoring task is started for the tenant id " + tenantId);
}
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE);
TriggerInfo triggerInfo = new TriggerInfo();
@ -64,9 +63,9 @@ public class TaskScheduleServiceImpl implements TaskScheduleService {
Map<String, String> properties = new HashMap<>();
properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId));
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId);
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo);
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
@ -86,9 +85,9 @@ public class TaskScheduleServiceImpl implements TaskScheduleService {
public void stopTask() throws PolicyMonitoringTaskException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId);
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE);
taskManager.deleteTask(taskName);
} catch (TaskException e) {
String msg = "Error occurred while deleting the task for tenant " + PrivilegedCarbonContext.
@ -102,10 +101,10 @@ public class TaskScheduleServiceImpl implements TaskScheduleService {
public void updateTask(int monitoringFrequency) throws PolicyMonitoringTaskException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId);
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE);
taskManager.deleteTask(taskName);
@ -117,7 +116,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService {
Map<String, String> properties = new HashMap<>();
properties.put("tenantId", String.valueOf(tenantId));
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo);
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());

@ -32,14 +32,18 @@ public final class PolicyManagementConstants {
public static final String BLOCK = "BLOCK";
public static final String TASK_TYPE = "MONITORING_TASK";
public static final String TASK_NAME = "MONITORING";
public static final String TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask";
public static final String MONITORING_TASK_TYPE = "MONITORING_TASK";
public static final String MONITORING_TASK_NAME = "MONITORING";
public static final String MONITORING_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask";
public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER";
public static final String DM_CACHE = "DM_CACHE";
public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK";
public static final String DELEGATION_TASK_NAME = "DELEGATION";
public static final String DELEGATION_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask";
}

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

@ -28,9 +28,18 @@ 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.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
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;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.services.PolicyMonitoringServiceTest;
import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.sql.DataSource;
@ -50,6 +59,12 @@ public abstract class BasePolicyManagementDAOTest {
public void setupDataSource() throws Exception {
this.initDatSource();
this.initSQLScript();
this.initialize();
this.initiatePrivilegedCaronContext();
}
public void initialize() throws TaskException {
}
public void initDatSource() throws Exception {

@ -29,21 +29,21 @@ 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.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
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.PolicyMonitoringTaskException;
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;
@ -70,20 +70,19 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
List<Device> devices = service.getAllDevices(ANDROID);
for (Policy policy : policies) {
log.debug(policy.getPolicyName() + "-----P");
log.debug("Policy Name : " + policy.getPolicyName());
}
for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- D");
log.debug("Device Name : " + device.getDeviceIdentifier());
}
identifier.setType(ANDROID);
identifier.setId(devices.get(0).getDeviceIdentifier());
PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl();
administratorPoint.setPolicyUsed(identifier, policies.get(0));
// PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl();
//
// administratorPoint.setPolicyUsed(identifier, policies.get(0));
}
@ -116,9 +115,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
DeviceManagementDataHolder.getInstance().setOperationManager(operationManager);
if (policy != null) {
log.debug(policy.getId());
log.debug(policy.getPolicyName());
log.debug(policy.getCompliance());
}
MonitoringManager monitoringManager = new MonitoringManagerImpl();
@ -137,7 +138,6 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
PolicyComplianceException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
monitoringServiceTest);
@ -159,14 +159,17 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
PolicyManager manager = new PolicyManagerImpl();
Policy policy = manager.getAppliedPolicyToDevice(identifier);
if(policy != null) {
Object ob = new Object();
monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob);
}
}
@Test(dependsOnMethods = ("checkComplianceFromMonitoringService"))
public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, PolicyManagementException {
public void checkCompliance() throws DeviceManagementException, PolicyComplianceException,
PolicyManagementException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
@ -191,4 +194,5 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
monitoringManager.checkPolicyCompliance(identifier, ob);
}
}

@ -76,25 +76,17 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
DeviceType type = DeviceTypeCreator.getDeviceType();
devices = DeviceCreator.getDeviceList(type);
devices.addAll(DeviceCreator.getDeviceList2(type));
devices.addAll(DeviceCreator.getDeviceList3(type));
devices.addAll(DeviceCreator.getDeviceList4(type));
devices.addAll(DeviceCreator.getDeviceList5(type));
devices.addAll(DeviceCreator.getDeviceList6(type));
for (Device device : devices) {
int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -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) {
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);
for (Device device : devices2) {
log.debug(device.getDeviceIdentifier());
}
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
@ -103,6 +95,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
log.debug("Printing device taken by calling the service layer with device type.");
List<Device> devices3 = service.getAllDevices("android");
log.debug("Device list size ...! " + devices3.size());
for (Device device : devices3) {
log.debug(device.getDeviceIdentifier());
}
@ -112,12 +105,14 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addDevice"))
public void addFeatures() throws FeatureManagementException {
FeatureManager featureManager = new FeatureManagerImpl();
//This test case was removed because architecture was changed
// FeatureManager featureManager = new FeatureManagerImpl();
featureList = FeatureCreator.getFeatureList();
//featureManager.addFeatures(featureList);
for (Feature feature : featureList) {
// featureManager.addFeatures(featureList);
// for (Feature feature : featureList) {
// featureManager.addFeature(feature);
}
// }
}
@ -125,15 +120,15 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
public void addProfileFeatures() throws ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList);
profileManager.addProfile(profile);
profileFeatureList = profile.getProfileFeaturesList();
Profile profile = ProfileCreator.getProfile2(FeatureCreator.getFeatureList2());
// profileManager.addProfile(profile);
// profileFeatureList = profile.getProfileFeaturesList();
}
@Test(dependsOnMethods = ("addProfileFeatures"))
public void addPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList);
Profile profile = ProfileCreator.getProfile5(FeatureCreator.getFeatureList5());
profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy(profile);
@ -171,10 +166,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addPolicyToDevice"))
public void addNewPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList);
Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3());
profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy2(profile);
Policy policy = PolicyCreator.createPolicy2(profile);
policyManager.addPolicy(policy);
}
@ -182,10 +177,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addPolicyToDevice"))
public void addThirdPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList);
Profile profile = ProfileCreator.getProfile4(FeatureCreator.getFeatureList4());
profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy4(profile);
Policy policy = PolicyCreator.createPolicy4(profile);
policyManager.addPolicy(policy);
}
@ -279,14 +274,28 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("getRoleRelatedPolicy"))
public void addSecondPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList);
Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList());
profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy3(profile);
Policy policy = PolicyCreator.createPolicy3(profile);
policyManager.addPolicy(policy);
}
@Test(dependsOnMethods = ("getDeviceTypeRelatedPolicy"))
@Test(dependsOnMethods = ("addSecondPolicy"))
public void updatedPolicy() throws PolicyManagementException {
PolicyManager policyManager = new PolicyManagerImpl();
Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3());
Policy policy = PolicyCreator.createPolicy3(profile);
policy.setPolicyName("Policy_05");
policy = policyManager.addPolicy(policy);
List<String> users = new ArrayList<>();
users.add("Udara");
users.add("Dileesha");
policy.setUsers(users);
policyManager.updatePolicy(policy);
}
@Test(dependsOnMethods = ("updatedPolicy"))
public void getRoleRelatedPolicySecondTime() throws PolicyManagementException {
PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl();
@ -348,7 +357,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl();
policyAdministratorPoint.deletePolicy(1);
log.debug("First policy deleted.");
log.debug("First policy deleted..!");
}
@ -362,13 +371,14 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
List<Device> devices = service.getAllDevices("android");
for (Policy policy : policies) {
log.debug(policy.getPolicyName() + "-----P");
log.debug("Policy Name : " + policy.getPolicyName());
}
for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- D");
log.debug("Device Name : " + device.getDeviceIdentifier());
}
}
}

@ -0,0 +1,136 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.mgt.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest;
import java.util.Collections;
import java.util.List;
public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest {
private static final String ANDROID = "android";
private static final Log log = LogFactory.getLog(PolicyEvaluationTestCase.class);
@BeforeClass
@Override
public void init() throws Exception {
PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest();
PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint);
}
@Test
public void activatePolicies() throws PolicyManagementException, TaskException {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP();
List<Policy> policies = policyManagerService.getPolicies(ANDROID);
for (Policy policy : policies) {
log.debug("Policy status : " + policy.getPolicyName() + " - " + policy.isActive() + " - " + policy
.isUpdated() + " Policy id : " + policy.getId());
if (!policy.isActive()) {
administratorPoint.activatePolicy(policy.getId());
}
}
// This cannot be called due to task service cannot be started from the
//administratorPoint.publishChanges();
}
@Test(dependsOnMethods = ("activatePolicies"))
public void getEffectivePolicy() throws DeviceManagementException, PolicyEvaluationException {
log.debug("Getting effective policy for device started ..........");
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> devices = service.getAllDevices(ANDROID);
PolicyEvaluationPoint evaluationPoint = PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint();
for (Device device : devices) {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setType(device.getType());
identifier.setId(device.getDeviceIdentifier());
Policy policy = evaluationPoint.getEffectivePolicy(identifier);
if (policy != null) {
log.debug("Name of the policy applied to device is " + policy.getPolicyName());
} else {
log.debug("No policy is applied to device.");
}
}
}
@Test(dependsOnMethods = ("getEffectivePolicy"))
public void updatePriorities() throws PolicyManagementException, TaskException {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP();
List<Policy> policies = administratorPoint.getPolicies();
log.debug("Re-enforcing policy started...!");
int sixe = policies.size();
sortPolicies(policies);
int x = 0;
for (Policy policy : policies) {
policy.setPriorityId(sixe - x);
x++;
}
administratorPoint.updatePolicyPriorities(policies);
// administratorPoint.publishChanges();
}
@Test(dependsOnMethods = ("updatePriorities"))
public void checkDelegations() {
log.debug("Delegation methods calls started because tasks cannot be started due to osgi constraints.....!");
DelegationTask delegationTask = new DelegationTask();
delegationTask.execute();
}
public void sortPolicies(List<Policy> policyList) {
Collections.sort(policyList);
}
}

@ -0,0 +1,84 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.policy.mgt.core.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
import java.util.Collections;
import java.util.List;
public class SimplePolicyEvaluationTest implements PolicyEvaluationPoint {
private static final Log log = LogFactory.getLog(SimplePolicyEvaluationTest.class);
@Override
public Policy getEffectivePolicy(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException {
Policy policy = new Policy();
List<Policy> policyList;
PolicyAdministratorPoint policyAdministratorPoint;
PolicyInformationPoint policyInformationPoint;
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
try {
if (policyManagerService != null) {
policyInformationPoint = policyManagerService.getPIP();
PIPDevice pipDevice = policyInformationPoint.getDeviceData(deviceIdentifier);
policyList = policyInformationPoint.getRelatedPolicies(pipDevice);
for(Policy pol : policyList) {
log.debug("Policy used in evaluation - Name : " + pol.getPolicyName() );
}
sortPolicies(policyList);
if(!policyList.isEmpty()) {
policy = policyList.get(0);
} else {
return null;
}
policyAdministratorPoint = policyManagerService.getPAP();
policyAdministratorPoint.setPolicyUsed(deviceIdentifier, policy);
}
} catch (PolicyManagementException e) {
String msg = "Error occurred when retrieving the policy related data from policy management service.";
log.error(msg, e);
throw new PolicyEvaluationException(msg, e);
}
return policy;
}
@Override
public List<ProfileFeature> getEffectiveFeatures(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException {
return null;
}
public void sortPolicies(List<Policy> policyList) throws PolicyEvaluationException {
Collections.sort(policyList);
}
}

@ -27,10 +27,12 @@ import java.util.List;
public class DeviceCreator {
private static List<Device> deviceList = new ArrayList<Device>();
//private static ;
public static List<Device> getDeviceList(DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(1);
device.setType(deviceType.getName());
@ -42,25 +44,131 @@ public class DeviceCreator {
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
Device device1 = new Device();
device1.setId(1);
device1.setType(deviceType.getName());
device1.setName("Nexus 5");
device1.setDeviceIdentifier("def456");
EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo();
enrolmentInfo1.setOwner("Manoj");
enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE);
device1.setEnrolmentInfo(enrolmentInfo);
// Device device1 = new Device();
// device1.setId(2);
// device1.setType(deviceType.getName());
// device1.setName("Nexus 5");
// device1.setDeviceIdentifier("def456");
// EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo();
// enrolmentInfo1.setOwner("Manoj");
// enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
// enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE);
// device1.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
// deviceList.add(device1);
return deviceList;
}
public static List<Device> getDeviceList2 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(2);
device.setType(deviceType.getName());
device.setName("Apple 5S");
device.setDeviceIdentifier("def123");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Dilshan");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
return deviceList;
}
public static List<Device> getDeviceList3 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(3);
device.setType(deviceType.getName());
device.setName("Apple 6 Large");
device.setDeviceIdentifier("xxxx123");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Harshan");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
return deviceList;
}
public static List<Device> getDeviceList4 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(4);
device.setType(deviceType.getName());
device.setName("HTC M");
device.setDeviceIdentifier("ppp456");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Dilan");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
return deviceList;
}
public static List<Device> getDeviceList5 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(5);
device.setType(deviceType.getName());
device.setName("Sony Experia L");
device.setDeviceIdentifier("ssss123");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Milan");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
// deviceList.add(device2);
return deviceList;
}
public static List<Device> getDeviceList6 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device();
device.setId(6);
device.setType(deviceType.getName());
device.setName("Alcatel RTS");
device.setDeviceIdentifier("ttt123");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Dileesha");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
return deviceList;
}
public static Device getSingleDevice() {
return deviceList.get(0);
Device device = new Device();
device.setId(1);
device.setType("android");
device.setName("Galaxy S6");
device.setDeviceIdentifier("abc123");
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner("Geeth");
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo);
return device;
}
}

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

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

@ -41,4 +41,66 @@ public class ProfileCreator {
return profile;
}
public static Profile getProfile2(List<Feature> features) {
Profile profile = new Profile();
DeviceType deviceType = new DeviceType();
deviceType.setId(1);
deviceType.setName("android");
profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features));
profile.setProfileName("Test Profile 2");
profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
profile.setDeviceType(deviceType);
return profile;
}
public static Profile getProfile3(List<Feature> features) {
Profile profile = new Profile();
DeviceType deviceType = new DeviceType();
deviceType.setId(1);
deviceType.setName("android");
profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features));
profile.setProfileName("Test Profile 3");
profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
profile.setDeviceType(deviceType);
return profile;
}
public static Profile getProfile4(List<Feature> features) {
Profile profile = new Profile();
DeviceType deviceType = new DeviceType();
deviceType.setId(1);
deviceType.setName("android");
profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features));
profile.setProfileName("Test Profile 4");
profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
profile.setDeviceType(deviceType);
return profile;
}
public static Profile getProfile5(List<Feature> features) {
Profile profile = new Profile();
DeviceType deviceType = new DeviceType();
deviceType.setId(1);
deviceType.setName("android");
profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features));
profile.setProfileName("Test Profile 5");
profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
profile.setDeviceType(deviceType);
return profile;
}
}

@ -0,0 +1,51 @@
<tasks-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<!--
The currently running server mode; possible values are:-
STANDALONE, CLUSTERED, REMOTE, AUTO.
In AUTO mode, the server startup checks whether clustering is enabled in the system,
if so, CLUSTERED mode will be used, or else, the the server mode will be STANDALONE.
-->
<taskServerMode>AUTO</taskServerMode>
<!--
To be used in CLUSTERED mode to notify how many servers are there in
the task server cluster, the servers wait till this amount of servers
are activated before the tasks are scheduled -->
<taskServerCount>2</taskServerCount>
<!-- The default location resolver configuration -->
<defaultLocationResolver>
<locationResolverClass>org.wso2.carbon.ntask.core.impl.RoundRobinTaskLocationResolver</locationResolverClass>
</defaultLocationResolver>
<!--
if task-type-pattern matches and task-name-pattern matches, check existing addresses of address-pattern,
and if addresses exist, select address in round-robin fashion, if not move onto next rule in sequence.
<property name="rule-[order]">[task-type-pattern],[task-name-pattern],[address-pattern]</property>
-->
<!--defaultLocationResolver>
<locationResolverClass>org.wso2.carbon.ntask.core.impl.RuleBasedLocationResolver</locationResolverClass>
<properties>
<property name="rule-1">HIVE_TASK,.*,192.168.2.*</property>
<property name="rule-5">.*,.*,.*</property>
</properties>
</defaultLocationResolver-->
<!-- The address to which the remote task server should dispatch the trigger messages to,
usually this would be an endpoint to a load balancer -->
<taskClientDispatchAddress>https://localhost:9448</taskClientDispatchAddress>
<!-- The address of the remote task server -->
<remoteServerAddress>https://localhost:9443</remoteServerAddress>
<!-- The username to authenticate to the remote task server -->
<remoteServerUsername>admin</remoteServerUsername>
<!-- The password to authenticate to the remote task server -->
<remoteServerPassword>admin</remoteServerPassword>
<!-- Below contain a sample to be used when using with secure vault -->
<!--remoteServerPassword svns:secretAlias="remote.task.server.password"></remoteServerPassword-->
</tasks-configuration>

@ -33,8 +33,8 @@
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>-->
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>-->
<!--<userName>root</userName>-->
<!--<pwd></pwd>-->
<!--<User>root</User>-->
<!--<Password></Password>-->
</DataSourceConfig>

@ -109,7 +109,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS (
APPLICATIONS BLOB DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_applications_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
--- POLICY RELATED TABLES ----
@ -143,7 +143,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL,
COMPLIANCE VARCHAR(100) NULL,
PRIORITY INT NOT NULL ,
PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )
@ -345,6 +347,19 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT (
ID INT NOT NULL AUTO_INCREMENT,
POLICY_ID INT NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_CHANGE_MGT_POLICY
FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES FINISHED --

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

@ -128,7 +128,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL,
COMPLIANCE VARCHAR(100) NULL,
PRIORITY INT NOT NULL ,
PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )
@ -312,6 +314,20 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
);
CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT (
ID INT NOT NULL AUTO_INCREMENT,
POLICY_ID INT NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_CHANGE_MGT_POLICY
FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ID INT NOT NULL AUTO_INCREMENT,
COMPLIANCE_STATUS_ID INT NOT NULL,

Loading…
Cancel
Save