Add policy type

3.x.x
Pahansith Gunathilake 5 years ago committed by Dharmakeerthi Lasantha
parent d683d0c93f
commit db8645e6c5

@ -23,6 +23,7 @@ import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
@ -102,6 +103,19 @@ public class PolicyWrapper {
required = true)
private List<DeviceGroupWrapper> deviceGroups;
@ApiModelProperty(name = "policyType", value = "Type of the corresponding policy",
required = true)
@NotNull
private String policyType;
public String getPolicyType() {
return policyType;
}
public void setPolicyType(String policyType) {
this.policyType = policyType;
}
public Profile getProfile() {
return profile;
}

@ -697,4 +697,87 @@ public interface PolicyManagementService {
@PathParam("deviceId")
@Size(max = 45)
String deviceId);
@GET
@Path("/type/{policyType}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Policies",
responseContainer = "List",
notes = "Retrieve the details of all the policies filtered by policy type in WSO2 EMM.",
response = Policy.class,
tags = "Device Policy Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:policies:get-details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched policies.",
response = Policy.class,
responseContainer = "List",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}
),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version " +
"of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = ("Internal Server Error. \n Server error occurred while fetching the policies."),
response = ErrorResponse.class)
})
Response getPolicies(@ApiParam(
name = "policyType",
value = "The policy type, such as general policy, Geo policy.",
required = true)
@PathParam("policyType")
String policyType,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items",
required = false,
defaultValue = "0")
@QueryParam("offset")
int offset,
@ApiParam(
name = "limit",
value = "Provide how many policy details you require from the starting pagination index/offset.",
required = false,
defaultValue = "5")
@QueryParam("limit")
int limit
);
}

@ -123,6 +123,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
policy.setUsers(policyWrapper.getUsers());
policy.setCompliance(policyWrapper.getCompliance());
policy.setDeviceGroups(policyWrapper.getDeviceGroups());
policy.setPolicyType(policyWrapper.getPolicyType());
//TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here.
List<Device> devices = new ArrayList<Device>();
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();
@ -398,4 +399,33 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity(policy).build();
}
@GET
@Path("/type/{policyType}")
@Override
public Response getPolicies(
@PathParam("policyType") String policyType,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
RequestValidationUtil.validatePaginationParameters(offset, limit);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<Policy> policies;
List<Policy> filteredPolicies;
PolicyList targetPolicies = new PolicyList();
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicies(policyType);
targetPolicies.setCount(policies.size());
filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit);
targetPolicies.setList(filteredPolicies);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving all available policies";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(targetPolicies).build();
}
}

@ -177,6 +177,12 @@ public class Policy implements Comparable<Policy>, Serializable {
example = "[]")
private List<DeviceGroupWrapper> deviceGroups;
@ApiModelProperty(
name = "policyType",
value = "Type of the corresponding policy",
required = true,
example = "GENERAL")
private String policyType;
@XmlElement
public int getId() {
@ -341,6 +347,14 @@ public class Policy implements Comparable<Policy>, Serializable {
this.deviceGroups = deviceGroups;
}
public String getPolicyType() {
return policyType;
}
public void setPolicyType(String policyType) {
this.policyType = policyType;
}
@Override
public int compareTo(Policy o) {
if (this.priorityId == o.priorityId)

@ -458,6 +458,8 @@ var savePolicy = function (policy, isActive, serviceURL) {
payload["deviceGroups"] = policy["selectedGroups"];
}
payload["policyType"] = "GENERAL";
invokerUtil.post(
serviceURL,
payload,

@ -102,6 +102,18 @@ public class PolicyWrapper {
required = true)
private List<DeviceGroupWrapper> deviceGroups;
@ApiModelProperty(name = "policyType", value = "Type of the corresponding policy",
required = true)
private String policyType;
public String getPolicyType() {
return policyType;
}
public void setPolicyType(String policyType) {
this.policyType = policyType;
}
public Profile getProfile() {
return profile;
}

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

@ -155,4 +155,11 @@ public interface PolicyAdministratorPoint {
List<Profile> getProfiles() throws PolicyManagementException;
int getPolicyCount() throws PolicyManagementException;
/**
* @param policyType type of the policy
* @return policy list of the specific type
* @throws PolicyManagementException
*/
List<Policy> getPolicies(String policyType) throws PolicyManagementException;
}

@ -113,4 +113,13 @@ public interface PolicyCacheManager {
* @return - Id of the policy.
*/
int getPolicyIdOfDevice(int deviceId);
/**
* This method will return the all policies belongs to the specific type.
*
* @param policyType - type of the policy
* @return - list of policies
* @throws PolicyManagementException
*/
List<Policy> getAllPolicies(String policyType) throws PolicyManagementException;
}

@ -30,6 +30,7 @@ import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.cache.Cache;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@ -74,31 +75,13 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
@Override
public List<Policy> getAllPolicies() throws PolicyManagementException {
Cache<Integer, List<Policy>> lCache = getPolicyListCache();
if (!lCache.containsKey(1)) {
PolicyManager policyManager = new PolicyManagerImpl();
this.addAllPolicies(policyManager.getPolicies());
}
updateCache(lCache);
if (log.isDebugEnabled()) {
List<Policy> cachedPolicy = lCache.get(1);
for (Policy policy : cachedPolicy) {
log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy.
getPolicyName() + " Activated : " + policy.isActive());
List<String> users = policy.getUsers();
for (String user : users) {
log.debug("Users in cached policy : " + user);
}
List<String> roles = policy.getRoles();
for (String role : roles) {
log.debug("Roles in cached policy : " + role);
}
}
showDebugLog(lCache);
}
lCache = getPolicyListCache();
return lCache.get(1);
}
@Override
@ -218,4 +201,47 @@ public class PolicyCacheManagerImpl implements PolicyCacheManager {
return 0;
}
@Override
public List<Policy> getAllPolicies(String policyType) throws PolicyManagementException {
Cache<Integer, List<Policy>> lCache = getPolicyListCache();
updateCache(lCache);
if (log.isDebugEnabled()) {
showDebugLog(lCache);
}
lCache = getPolicyListCache();
List<Policy> policyListByType = new ArrayList<>();
List<Policy> cachedPolicyList = lCache.get(1);
Iterator<Policy> iterator = cachedPolicyList.iterator();
while (iterator.hasNext()) {
Policy policy = iterator.next();
if (policy.getPolicyType().equals(policyType)) {
policyListByType.add(policy);
}
}
return policyListByType;
}
private void updateCache(Cache<Integer, List<Policy>> lCache) throws PolicyManagementException {
if (!lCache.containsKey(1)) {
PolicyManager policyManager = new PolicyManagerImpl();
this.addAllPolicies(policyManager.getPolicies());
}
}
private void showDebugLog(Cache<Integer, List<Policy>> lCache) {
List<Policy> cachedPolicy = lCache.get(1);
for (Policy policy : cachedPolicy) {
log.debug("Policy id in cache .. : " + policy.getId() + " policy name : " + policy.
getPolicyName() + " Activated : " + policy.isActive());
List<String> users = policy.getUsers();
for (String user : users) {
log.debug("Users in cached policy : " + user);
}
List<String> roles = policy.getRoles();
for (String role : roles) {
log.debug("Roles in cached policy : " + role);
}
}
}
}

@ -150,4 +150,6 @@ public interface PolicyDAO {
HashMap<Integer, Integer> getAppliedPolicyIds() throws PolicyManagerDAOException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException;
List<Policy> getAllPolicies(String policyType) throws PolicyManagerDAOException;
}

@ -979,21 +979,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
Policy policy = new Policy();
policy.setId(resultSet.getInt("ID"));
policy.setProfileId(resultSet.getInt("PROFILE_ID"));
policy.setPolicyName(resultSet.getString("NAME"));
policy.setTenantId(tenantId);
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")));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policies.add(policy);
}
return policies;
return this.extractPolicyListFromDbResult(resultSet, tenantId);
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while reading the policies from the database", e);
} finally {
@ -1437,7 +1423,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
"UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
"UPDATED, ACTIVE, DESCRIPTION, POLICY_TYPE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, new String[]{"id"});
stmt.setString(1, policy.getPolicyName());
@ -1449,6 +1435,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(7, 0);
stmt.setInt(8, 0);
stmt.setString(9, policy.getDescription());
stmt.setString(10, policy.getPolicyType());
int affectedRows = stmt.executeUpdate();
@ -1704,4 +1691,57 @@ public class PolicyDAOImpl implements PolicyDAO {
return devicePolicyIds;
}
@Override
public List<Policy> getAllPolicies(String policyType) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT ID, " +
"PROFILE_ID, " +
"NAME, " +
"PRIORITY, " +
"COMPLIANCE, " +
"OWNERSHIP_TYPE, " +
"UPDATED, " +
"ACTIVE, " +
"DESCRIPTION, " +
"POLICY_TYPE "+
"FROM DM_POLICY WHERE TENANT_ID = ? AND POLICY_TYPE = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.setString(2, policyType);
resultSet = stmt.executeQuery();
return this.extractPolicyListFromDbResult(resultSet, tenantId);
} catch (SQLException e) {
String msg = "Error occurred while reading the policies from the database ";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
private List<Policy> extractPolicyListFromDbResult(ResultSet resultSet, int tenantId) throws SQLException {
List<Policy> policies = new ArrayList<>();
while (resultSet.next()) {
Policy policy = new Policy();
policy.setId(resultSet.getInt("ID"));
policy.setProfileId(resultSet.getInt("PROFILE_ID"));
policy.setPolicyName(resultSet.getString("NAME"));
policy.setTenantId(tenantId);
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")));
policy.setDescription(resultSet.getString("DESCRIPTION"));
policy.setPolicyType(resultSet.getString("POLICY_TYPE"));
policies.add(policy);
}
return policies;
}
}

@ -377,4 +377,12 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
}
}
@Override
public List<Policy> getPolicies(String policyType) throws PolicyManagementException {
if (policyConfiguration.getCacheEnable()) {
return PolicyCacheManagerImpl.getInstance().getAllPolicies(policyType);
} else {
return policyManager.getPolicies(policyType);
}
}
}

@ -83,4 +83,6 @@ public interface PolicyManager {
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException;
List<Policy> getPolicies(String type) throws PolicyManagementException;
}

@ -626,25 +626,7 @@ public class PolicyManagerImpl implements PolicyManager {
try {
PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies();
for (Policy policy : policyList) {
for (Profile profile : profileList) {
if (policy.getProfileId() == profile.getProfileId()) {
policy.setProfile(profile);
}
}
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId());
if (!deviceGroupWrappers.isEmpty()) {
deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers);
}
policy.setDeviceGroups(deviceGroupWrappers);
}
Collections.sort(policyList);
this.buildPolicyList(policyList, profileList);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting all the policies.", e);
} catch (SQLException e) {
@ -1144,4 +1126,60 @@ public class PolicyManagerImpl implements PolicyManager {
return policyRevokeOperation;
}
@Override
public List<Policy> getPolicies(String type) throws PolicyManagementException {
List<Policy> policyList;
List<Profile> profileList;
try {
profileList = profileManager.getAllProfiles();
} catch (ProfileManagementException e) {
throw new PolicyManagementException("Error occurred while getting all the profiles.", e);
}
try {
PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies(type);
this.buildPolicyList(policyList, profileList);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while getting all the policies. ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (GroupManagementException e) {
String msg = "Error occurred while getting device groups. ";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
for (Policy policy : policyList) {
policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId()));
}
return policyList;
}
private void buildPolicyList(List<Policy> policyList, List<Profile> profileList)
throws PolicyManagerDAOException, GroupManagementException {
for (Policy policy : policyList) {
for (Profile profile : profileList) {
if (policy.getProfileId() == profile.getProfileId()) {
policy.setProfile(profile);
}
}
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId());
if (!deviceGroupWrappers.isEmpty()) {
deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers);
}
policy.setDeviceGroups(deviceGroupWrappers);
}
Collections.sort(policyList);
}
}

@ -130,6 +130,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest {
policy1.setDeviceGroups(deviceGroupWrappers);
List<Device> devices = new ArrayList<Device>();
policy1.setDevices(devices);
policy1.setPolicyType("GENERAL");
policy1.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
policy1 = policyManagerService.addPolicy(policy1);

@ -40,6 +40,7 @@ public class PolicyCreator {
policy.setCompliance("NOTIFY");
policy.setOwnershipType("COPE");
policy.setDescription("This is the first policy.");
policy.setPolicyType("GENERAL");
return policy;
}
@ -51,6 +52,7 @@ public class PolicyCreator {
policy.setPolicyName("Test_Policy_02");
policy.setGeneric(true);
policy.setProfile(profile);
policy.setPolicyType("GENERAL");
policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType()));
policy.setCompliance("ENFORCE");
@ -110,7 +112,7 @@ public class PolicyCreator {
policy.setRoles(roles);
policy.setCompliance("ENFORCE");
policy.setOwnershipType("BYOD");
policy.setPolicyType("GENERAL");
PolicyCriterion criterion = new PolicyCriterion();
@ -144,7 +146,7 @@ public class PolicyCreator {
policy.setCompliance("MONITOR");
policy.setOwnershipType("BYOD");
policy.setPolicyType("GENERAL");
List<String> roles = new ArrayList<String>();
roles.add("Role_04");
roles.add("Role_05");

@ -200,6 +200,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )

@ -193,6 +193,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )

@ -246,6 +246,7 @@ CREATE TABLE DM_POLICY (
PRIORITY INTEGER NOT NULL,
ACTIVE BIT NOT NULL DEFAULT 0,
UPDATED BIT NULL DEFAULT 0,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID) REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION ON UPDATE NO ACTION

@ -224,6 +224,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL,
POLICY_TYPE VARCHAR(45) NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )

@ -357,6 +357,7 @@ CREATE TABLE DM_POLICY (
PRIORITY NUMBER(10) NOT NULL,
ACTIVE NUMBER(10) NOT NULL,
UPDATED NUMBER(10) NULL,
POLICY_TYPE VARCHAR2(45) NULL,
CONSTRAINT PK_DM_PROFILE_DM_POLICY PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )

@ -194,6 +194,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
PRIORITY INTEGER NOT NULL,
ACTIVE INTEGER NOT NULL,
UPDATED INTEGER NULL,
POLICY_TYPE VARCHAR(45) NULL,
CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID )
REFERENCES DM_PROFILE (ID )

Loading…
Cancel
Save