revert-70aa11f8
charithag 9 years ago
commit 25ea00f26f

@ -72,10 +72,12 @@ public class APIPublisherUtil {
}
public static API getAPI(APIConfig config) throws APIManagementException {
APIProvider provider = config.getProvider();
String apiVersion = config.getVersion();
APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion);
API api = new API(id);
api.setApiOwner(config.getOwner());
String context = config.getContext();
context = context.startsWith("/") ? context : ("/" + context);
@ -84,12 +86,14 @@ public class APIPublisherUtil {
//Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
// This is to support the new Pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
context = checkAndSetVersionParam(context);
api.setContextTemplate(context);
context = updateContextWithVersion(config.getVersion(), context);
api.setContext(context);
api.setUrl(config.getEndpoint());
api.addAvailableTiers(provider.getTiers());
api.setEndpointSecured(true);
@ -97,12 +101,15 @@ public class APIPublisherUtil {
api.setTransports(config.getTransports());
api.setContextTemplate(config.getContextTemplate());
api.setUriTemplates(config.getUriTemplates());
Set<String> environements = new HashSet<>();
environements.add(API_PUBLISH_ENVIRONEMENT);
api.setEnvironments(environements);
Set<String> environments = new HashSet<>();
environments.add(API_PUBLISH_ENVIRONEMENT);
api.setEnvironments(environments);
Set<Tier> tiers = new HashSet<Tier>();
tiers.add(new Tier(APIConstants.UNLIMITED_TIER));
api.addAvailableTiers(tiers);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS);
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY);

@ -24,8 +24,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scannotation.AnnotationDB;
import org.scannotation.WarUrlFinder;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import javax.servlet.ServletContext;
import javax.ws.rs.*;
import java.io.IOException;
@ -45,17 +47,18 @@ public class AnnotationUtil {
private static final String PACKAGE_ORG_APACHE = "org.apache";
private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
private static final String AUTH_TYPE = "Any";
private static final String PROTOCOL_HTTP = "http";
private static final String SERVER_HOST = "carbon.local.ip";
private static final String HTTP_PORT = "httpPort";
public static final String DIR_WEB_INF_LIB = "/WEB-INF/lib";
public static final String STRING_ARR = "string_arr";
public static final String STRING = "string";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
private StandardContext context;
private Method[] pathClazzMethods;
private Class<Path> pathClazz;
Class<API> apiClazz;
private ClassLoader classLoader;
private ServletContext servletContext;
@ -68,6 +71,7 @@ public class AnnotationUtil {
/**
* Scan the context for classes with annotations
*
* @return
* @throws IOException
*/
@ -89,6 +93,7 @@ public class AnnotationUtil {
/**
* Method identifies the URL templates and context by reading the annotations of a class
*
* @param entityClasses
* @return
*/
@ -107,38 +112,23 @@ public class AnnotationUtil {
APIResourceConfiguration apiResourceConfig = null;
try {
clazz = classLoader.loadClass(className);
Class<Path> apiClazz = (Class<Path>)
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
apiClazz = (Class<API>)
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API
.class.getName());
Annotation apiAnno = clazz.getAnnotation(apiClazz);
List<APIResource> resourceList;
apiResourceConfig = new APIResourceConfiguration();
if (apiAnno != null) {
Method[] apiClazzMethods = apiClazz.getMethods();
if (log.isDebugEnabled()) {
log.debug("Application Context root = " + servletContext.getContextPath());
}
try {
for(int k=0;k<apiClazzMethods.length;k++){
switch (apiClazzMethods[k].getName()){
case "name" :
apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "version" :
apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "context" :
apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "tags" :
apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno));
break;
}
}
apiResourceConfig = processAPIAnnotation(apiAnno);
// All the apis should map to same root "/"
String rootContext = servletContext.getContextPath();
pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName());
@ -177,7 +167,45 @@ public class AnnotationUtil {
return apiResourceConfigs;
}
private List<APIResource> getApiResources(String resourceRootContext, String apiRootContext, Method[] annotatedMethods) throws Throwable {
/**
* Iterate API annotation and build API Configuration
* @param apiAnno
* @return
* @throws Throwable
*/
private APIResourceConfiguration processAPIAnnotation(Annotation apiAnno) throws Throwable {
Method[] apiClazzMethods = apiClazz.getMethods();
APIResourceConfiguration apiResourceConfig = new APIResourceConfiguration();
for (int k = 0; k < apiClazzMethods.length; k++) {
switch (apiClazzMethods[k].getName()) {
case "name":
apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "version":
apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "context":
apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "tags":
apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno));
break;
}
}
return apiResourceConfig;
}
/**
* Get Resources for each API
* @param resourceRootContext
* @param apiRootContext
* @param annotatedMethods
* @return
* @throws Throwable
*/
private List<APIResource> getApiResources(String resourceRootContext, String apiRootContext,
Method[] annotatedMethods) throws Throwable {
List<APIResource> resourceList;
resourceList = new ArrayList<APIResource>();
for (Method method : annotatedMethods) {
@ -195,31 +223,19 @@ public class AnnotationUtil {
resource.setAuthType(AUTH_TYPE);
Annotation[] annotations = method.getDeclaredAnnotations();
for(int i=0; i<annotations.length; i++){
for (int i = 0; i < annotations.length; i++) {
if(annotations[i].annotationType().getName().equals(GET.class.getName())){
resource.setHttpVerb(HttpMethod.GET);
}
if(annotations[i].annotationType().getName().equals(POST.class.getName())){
resource.setHttpVerb(HttpMethod.POST);
}
if(annotations[i].annotationType().getName().equals(OPTIONS.class.getName())){
resource.setHttpVerb(HttpMethod.OPTIONS);
}
if(annotations[i].annotationType().getName().equals(DELETE.class.getName())){
resource.setHttpVerb(HttpMethod.DELETE);
}
if(annotations[i].annotationType().getName().equals(PUT.class.getName())){
resource.setHttpVerb(HttpMethod.PUT);
}
if(annotations[i].annotationType().getName().equals(Consumes.class.getName())){
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(Consumes.class.getName());
processHTTPMethodAnnotation(resource, annotations[i]);
if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) {
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(
Consumes.class.getName());
Method[] consumesClassMethods = consumesClass.getMethods();
Annotation consumesAnno = method.getAnnotation(consumesClass);
resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR));
}
if(annotations[i].annotationType().getName().equals(Produces.class.getName())){
Class<Produces> producesClass = (Class<Produces>) classLoader.loadClass(Produces.class.getName());
if (annotations[i].annotationType().getName().equals(Produces.class.getName())) {
Class<Produces> producesClass = (Class<Produces>) classLoader.loadClass(
Produces.class.getName());
Method[] producesClassMethods = producesClass.getMethods();
Annotation producesAnno = method.getAnnotation(producesClass);
resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR));
@ -231,12 +247,40 @@ public class AnnotationUtil {
return resourceList;
}
private String makeContextURLReady(String context){
if(context != null && !context.equalsIgnoreCase("")){
if(context.startsWith("/")){
/**
* Read Method annotations indicating HTTP Methods
* @param resource
* @param annotation
*/
private void processHTTPMethodAnnotation(APIResource resource, Annotation annotation) {
if (annotation.annotationType().getName().equals(GET.class.getName())) {
resource.setHttpVerb(HttpMethod.GET);
}
if (annotation.annotationType().getName().equals(POST.class.getName())) {
resource.setHttpVerb(HttpMethod.POST);
}
if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) {
resource.setHttpVerb(HttpMethod.OPTIONS);
}
if (annotation.annotationType().getName().equals(DELETE.class.getName())) {
resource.setHttpVerb(HttpMethod.DELETE);
}
if (annotation.annotationType().getName().equals(PUT.class.getName())) {
resource.setHttpVerb(HttpMethod.PUT);
}
}
/**
* Append '/' to the context and make it URL ready
* @param context
* @return
*/
private String makeContextURLReady(String context) {
if (context != null && !context.equalsIgnoreCase("")) {
if (context.startsWith("/")) {
return context;
}else{
return "/"+context;
} else {
return "/" + context;
}
}
return "";
@ -244,6 +288,7 @@ public class AnnotationUtil {
/**
* When an annotation and method is passed, this method invokes that executes said method against the annotation
*
* @param method
* @param annotation
* @param returnType
@ -252,11 +297,11 @@ public class AnnotationUtil {
*/
private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
switch (returnType){
switch (returnType) {
case STRING:
return (String) methodHandler.invoke(annotation, method, null);
case STRING_ARR:
return ((String[])methodHandler.invoke(annotation, method, null))[0];
return ((String[]) methodHandler.invoke(annotation, method, null))[0];
default:
return null;
}
@ -267,6 +312,6 @@ public class AnnotationUtil {
*/
private String[] invokeMethod(Method method, Annotation annotation) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
return ((String[])methodHandler.invoke(annotation, method, null));
return ((String[]) methodHandler.invoke(annotation, method, null));
}
}

@ -52,10 +52,21 @@ public interface GadgetDataService {
@SuppressWarnings("unused")
int getDeviceCount(Map<String, Object> filters);
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters);
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters);
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters);
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters);
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters);
}

@ -42,8 +42,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int totalDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
totalDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getTotalDeviceCount();
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
totalDeviceCount = -1;
return totalDeviceCount;
@ -58,8 +57,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int activeDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
activeDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getActiveDeviceCount();
activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
activeDeviceCount = -1;
return activeDeviceCount;
@ -74,8 +72,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int inactiveDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
inactiveDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getInactiveDeviceCount();
inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
inactiveDeviceCount = -1;
return inactiveDeviceCount;
@ -90,8 +87,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int removedDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
removedDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getRemovedDeviceCount();
removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
removedDeviceCount = -1;
return removedDeviceCount;
@ -106,8 +102,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int nonCompliantDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getNonCompliantDeviceCount();
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
nonCompliantDeviceCount = -1;
return nonCompliantDeviceCount;
@ -122,8 +117,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int unmonitoredDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
unmonitoredDeviceCount = -1;
return unmonitoredDeviceCount;
@ -153,8 +147,7 @@ class GadgetDataServiceImpl implements GadgetDataService {
int deviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getDeviceCount(filters);
deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
deviceCount = -1;
return deviceCount;
@ -164,13 +157,29 @@ class GadgetDataServiceImpl implements GadgetDataService {
return deviceCount;
}
@Override
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters) {
int featureNonCompliantDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
featureNonCompliantDeviceCount = -1;
return featureNonCompliantDeviceCount;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDeviceCount;
}
@Override
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) {
Map<String, Integer> deviceCountsByPlatforms = null;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getDeviceCountsByPlatforms(filters);
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getDeviceCountsByPlatforms(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
@ -179,13 +188,29 @@ class GadgetDataServiceImpl implements GadgetDataService {
return deviceCountsByPlatforms;
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) {
Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms = null;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDeviceCountsByPlatforms;
}
@Override
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) {
Map<String, Integer> deviceCountsByOwnershipTypes = null;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getDeviceCountsByOwnershipTypes(filters);
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getDeviceCountsByOwnershipTypes(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
@ -194,4 +219,21 @@ class GadgetDataServiceImpl implements GadgetDataService {
return deviceCountsByOwnershipTypes;
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) {
Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes = null;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDeviceCountsByOwnershipTypes =
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDeviceCountsByOwnershipTypes;
}
}

@ -28,6 +28,7 @@ import java.util.List;
@XmlRootElement
public class DeviceGroup implements Serializable {
private int id;
private String description;
private String name;
private Long dateOfCreation;
@ -36,6 +37,15 @@ public class DeviceGroup implements Serializable {
private List<GroupUser> users;
private List<String> roles;
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getDescription() {
return description;
@ -101,6 +111,7 @@ public class DeviceGroup implements Serializable {
protected DeviceGroup getGroup() {
DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setId(getId());
deviceGroup.setDescription(getDescription());
deviceGroup.setName(getName());
deviceGroup.setDateOfCreation(getDateOfCreation());

@ -83,7 +83,9 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
public void addDeviceProperties(Map<String, String> propertyMap, int deviceId) throws DeviceDetailsMgtDAOException {
if (propertyMap.isEmpty()) {
log.warn("Property map of device id :" + deviceId + " is empty.");
if(log.isDebugEnabled()) {
log.debug("Property map of device id :" + deviceId + " is empty.");
}
return;
}
Connection conn;

@ -36,6 +36,7 @@ public class DeviceGroupBuilder extends DeviceGroup {
* @param deviceGroup to decorate
*/
public DeviceGroupBuilder(DeviceGroup deviceGroup) {
this.setId(deviceGroup.getId());
this.setDescription(deviceGroup.getDescription());
this.setName(deviceGroup.getName());
this.setDateOfCreation(deviceGroup.getDateOfCreation());

@ -82,6 +82,14 @@ public interface GroupDAO {
*/
DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/**
* Get the groups of device with device id provided
* @param deviceId
* @return
* @throws GroupManagementDAOException
*/
List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant.
*

@ -178,6 +178,32 @@ public class GroupDAOImpl implements GroupDAO {
}
}
@Override
public List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroupBuilders = new ArrayList<>();
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" +
"G.OWNER FROM DM_GROUP AS G INNER JOIN DM_DEVICE_GROUP_MAP AS GM ON G.ID = GM.GROUP_ID " +
"WHERE GM.DEVICE_ID = ? AND GM.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
deviceGroupBuilders.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while obtaining information of Device Groups ", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupBuilders;
}
@Override
public List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException {

@ -44,14 +44,14 @@ public class QueryBuilderImpl implements QueryBuilder {
List<Condition> orColumns = new ArrayList<>();
List<Condition> otherANDColumns = new ArrayList<>();
List<Condition> otherORColumns = new ArrayList<>();
Condition locConditon = new Condition();
Condition locCondition = new Condition();
if (conditions.size() == 1) {
if (conditions.get(0).getKey().equalsIgnoreCase(Constants.LOCATION)) {
locConditon = conditions.get(0);
} else if (Utils.getDeviceDetailsColumnNames().containsKey(conditions.get(0).getKey()) ||
Utils.getDeviceLocationColumnNames().containsKey(conditions.get(0).getKey())) {
locCondition = conditions.get(0);
} else if (Utils.checkDeviceDetailsColumns(conditions.get(0).getKey()) ||
Utils.checkDeviceLocationColumns(conditions.get(0).getKey())) {
andColumns.add(conditions.get(0));
} else {
otherANDColumns.add(conditions.get(0));
@ -59,9 +59,9 @@ public class QueryBuilderImpl implements QueryBuilder {
} else {
for (Condition con : conditions) {
if (con.getKey().equalsIgnoreCase(Constants.LOCATION)) {
locConditon = con;
} else if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey()) ||
Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) {
locCondition = con;
} else if (Utils.checkDeviceDetailsColumns(con.getKey()) ||
Utils.checkDeviceLocationColumns(con.getKey())) {
if (con.getState().equals(Condition.State.AND)) {
andColumns.add(con);
} else if (con.getState().equals(Condition.State.OR)) {
@ -92,8 +92,8 @@ public class QueryBuilderImpl implements QueryBuilder {
if (!otherORColumns.isEmpty()) {
queries.put(Constants.PROP_OR, this.processORProperties(otherORColumns));
}
if (locConditon != null && locConditon.getValue() != null) {
queries.put(Constants.LOCATION, this.processLocation(locConditon));
if (locCondition != null && locCondition.getValue() != null) {
queries.put(Constants.LOCATION, this.processLocation(locCondition));
}
if (log.isDebugEnabled()) {
@ -112,10 +112,10 @@ public class QueryBuilderImpl implements QueryBuilder {
String querySuffix = "";
for (Condition con : conditions) {
if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) {
if (Utils.checkDeviceDetailsColumns(con.getKey())) {
querySuffix = querySuffix + " AND DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) +
con.getOperator() + con.getValue();
} else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) {
} else if (Utils.checkDeviceLocationColumns(con.getKey())) {
querySuffix = querySuffix + " AND DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) +
con.getOperator() + con.getValue();
}
@ -130,10 +130,10 @@ public class QueryBuilderImpl implements QueryBuilder {
String querySuffix = "";
for (Condition con : conditions) {
if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) {
if (Utils.checkDeviceDetailsColumns(con.getKey())) {
querySuffix = querySuffix + " OR DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) +
con.getOperator() + con.getValue();
} else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) {
} else if (Utils.checkDeviceLocationColumns(con.getKey())) {
querySuffix = querySuffix + " OR DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) +
con.getOperator() + con.getValue();
}

@ -28,43 +28,65 @@ import java.util.Map;
public class Utils {
public static Map<String, String> getDeviceDetailsColumnNames() {
private static Map<String, String> genericColumnsMap = new HashMap<>();
private static Map<String, String> locationColumnsMap = new HashMap<>();
static {
genericColumnsMap.put("deviceModel", "DEVICE_MODEL");
genericColumnsMap.put("vendor", "VENDOR");
genericColumnsMap.put("osVersion", "OS_VERSION");
genericColumnsMap.put("batteryLevel", "BATTERY_LEVEL");
genericColumnsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY");
genericColumnsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY");
genericColumnsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY");
genericColumnsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY");
genericColumnsMap.put("connectionType", "CONNECTION_TYPE");
genericColumnsMap.put("ssid", "SSID");
genericColumnsMap.put("cpuUsage", "CPU_USAGE");
genericColumnsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY");
genericColumnsMap.put("availableRAMMemory", "AVAILABLE_RAM_MEMORY");
genericColumnsMap.put("pluggedIn", "PLUGGED_IN");
locationColumnsMap.put("latitude", "LATITUDE");
locationColumnsMap.put("longitude", "LONGITUDE");
locationColumnsMap.put("street1", "STREET1");
locationColumnsMap.put("street2", "STREET2");
locationColumnsMap.put("city", "CITY");
locationColumnsMap.put("state", "ZIP");
locationColumnsMap.put("zip", "STATE");
locationColumnsMap.put("country", "COUNTRY");
}
Map<String, String> colonmsMap = new HashMap<>();
colonmsMap.put("deviceModel", "DEVICE_MODEL");
colonmsMap.put("vendor", "VENDOR");
colonmsMap.put("osVersion", "OS_VERSION");
colonmsMap.put("batteryLevel", "BATTERY_LEVEL");
colonmsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY");
colonmsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY");
colonmsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY");
colonmsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY");
colonmsMap.put("connectionType", "CONNECTION_TYPE");
colonmsMap.put("ssid", "SSID");
colonmsMap.put("cpuUsage", "CPU_USAGE");
colonmsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY");
colonmsMap.put("availableRAMMemory", "AVAILABLE_RAM_MEMORY");
colonmsMap.put("pluggedIn", "PLUGGED_IN");
return colonmsMap;
public static Map<String, String> getDeviceDetailsColumnNames() {
return genericColumnsMap;
}
public static Map<String, String> getDeviceLocationColumnNames() {
Map<String, String> colonmsMap = new HashMap<>();
colonmsMap.put("latitude", "LATITUDE");
colonmsMap.put("longitude", "LONGITUDE");
colonmsMap.put("street1", "STREET1");
colonmsMap.put("street2", "STREET2");
colonmsMap.put("city", "CITY");
colonmsMap.put("state", "ZIP");
colonmsMap.put("zip", "STATE");
colonmsMap.put("country", "COUNTRY");
return colonmsMap;
return locationColumnsMap;
}
public static boolean checkDeviceDetailsColumns(String str) {
if (genericColumnsMap.containsKey(str)) {
return true;
}
if (genericColumnsMap.containsValue(str)) {
return true;
}
return false;
}
public static boolean checkDeviceLocationColumns(String str) {
if (locationColumnsMap.containsKey(str)) {
return true;
}
if (locationColumnsMap.containsValue(str)) {
return true;
}
return false;
}
public static List<String> convertStringToList(String str) {

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.List;
@ -73,6 +74,15 @@ public interface GroupManagementProviderService {
*/
DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException;
/**
* Get the device group provided the device group id.
* @param groupId
* @return
* @throws GroupManagementException
*/
DeviceGroup getGroup(int groupId) throws GroupManagementException;
/**
* Get list of device groups matched with %groupName%
*
@ -288,4 +298,12 @@ public interface GroupManagementProviderService {
*/
List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException;
/**
* Get the group of device.
* @param deviceIdentifier
* @return
* @throws GroupManagementException
*/
List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException;
}

@ -22,6 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -190,7 +191,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
return deviceGroupBuilder;
}
@SuppressWarnings("Duplicates")
private DeviceGroupBuilder getGroupBuilder(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker;
try {
@ -210,6 +211,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
return groupBroker;
}
/**
* {@inheritDoc}
*/
@Override
public DeviceGroup getGroup(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker = this.getGroupBuilder(groupId);
if (groupBroker != null) {
groupBroker.setUsers(this.getUsers(groupBroker.getGroupId()));
groupBroker.setRoles(this.getRoles(groupBroker.getGroupId()));
}
return groupBroker.getGroup();
}
/**
* {@inheritDoc}
*/
@ -763,6 +777,30 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
@Override
public List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException {
DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl();
List<DeviceGroup> deviceGroups = new ArrayList<>();
try {
Device device = managementProviderService.getDevice(deviceIdentifier);
GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> builders = groupDAO.getGroups(device.getId(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
for (DeviceGroupBuilder d : builders){
deviceGroups.add(d.getGroup());
}
} catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while retrieving the device details.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving device groups.", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening database connection.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
return deviceGroups;
}
private DeviceGroupBuilder extractNewGroupFromRole(Map<Integer, DeviceGroup> groups, String role)
throws GroupManagementException {
try {

@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
@ -218,7 +219,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(30) NOT NULL,
FEATURE_CODE VARCHAR(100) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL ,
CONTENT BLOB NULL DEFAULT NULL,
@ -350,7 +351,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ID INT NOT NULL AUTO_INCREMENT,
COMPLIANCE_STATUS_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
FEATURE_CODE VARCHAR(15) NOT NULL,
FEATURE_CODE VARCHAR(100) NOT NULL,
STATUS INT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS
@ -385,7 +386,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION (
LOCATION_URL VARCHAR(100) DEFAULT NULL,
IMAGE_URL VARCHAR(100) DEFAULT NULL,
APP_PROPERTIES BLOB NULL,
MEMORY_USAGE DECIMAL(5) NULL,
MEMORY_USAGE INTEGER(10) NULL,
TENANT_ID INTEGER NOT NULL,
PRIMARY KEY (ID)
);
@ -483,3 +484,54 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- POLICY AND DEVICE GROUP MAPPING --
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_GROUP_ID INT NOT NULL,
POLICY_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
FOREIGN KEY (DEVICE_GROUP_ID)
REFERENCES DM_GROUP (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
REFERENCES DM_POLICY (ID , ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- END OF POLICY AND DEVICE GROUP MAPPING --
CREATE VIEW DEVICES_VIEW_1 AS
SELECT
DEVICE_INFO.DEVICE_ID,
DEVICE_INFO.PLATFORM,
DEVICE_INFO.OWNERSHIP,
DEVICE_INFO.CONNECTIVITY_STATUS,
IFNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID,
IFNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT,
DEVICE_INFO.TENANT_ID
FROM
(SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE_TYPE.NAME AS PLATFORM,
DM_ENROLMENT.OWNERSHIP AS OWNERSHIP,
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
DM_DEVICE.TENANT_ID AS TENANT_ID
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
LEFT JOIN
(SELECT
DEVICE_ID,
POLICY_ID,
STATUS AS IS_COMPLIANT
FROM
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_INFO.DEVICE_ID;

@ -62,8 +62,8 @@ public class AnnotationUtil {
private static final String PACKAGE_ORG_APACHE = "org.apache";
private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
public static final String STRING_ARR = "string_arr";
public static final String STRING = "string";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
private Class<org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature>
featureAnnotationClazz;
private ClassLoader classLoader;
@ -164,7 +164,8 @@ public class AnnotationUtil {
return featureList;
}
private Map<String, Object> processParamAnnotations(Map<String, Object> apiParams, Method currentMethod) throws Throwable{
private Map<String, Object> processParamAnnotations(Map<String, Object> apiParams, Method currentMethod)
throws Throwable{
try {
apiParams.put("pathParams", processParamAnnotations(currentMethod, PathParam.class));
apiParams.put("queryParams", processParamAnnotations(currentMethod, QueryParam.class));
@ -196,6 +197,12 @@ public class AnnotationUtil {
return params;
}
/**
* Read Method annotations indicating HTTP Methods
* @param feature
* @param currentAnnotation
* @return
*/
private Feature processHttpMethodAnnotation(Feature feature, Annotation currentAnnotation) {
//Extracting method with which feature is exposed
if (currentAnnotation.annotationType().getName().equals(GET.class.getName())) {
@ -212,6 +219,13 @@ public class AnnotationUtil {
return feature;
}
/**
* Read Feature annotation and Identify Features
* @param feature
* @param currentMethod
* @return
* @throws Throwable
*/
private Feature processFeatureAnnotation(Feature feature, Method currentMethod) throws Throwable{
Method[] featureAnnoMethods = featureAnnotationClazz.getMethods();
Annotation featureAnno = currentMethod.getAnnotation(featureAnnotationClazz);
@ -234,6 +248,12 @@ public class AnnotationUtil {
return feature;
}
/**
* Get value depicted by Path Annotation
* @param currentMethod
* @return
* @throws Throwable
*/
public String getPathAnnotationValue(Method currentMethod) throws Throwable{
String uri = "";
try {

@ -0,0 +1,61 @@
/*
* Copyright (c) 2016, 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.common;
public class DeviceGroupWrapper {
private int id;
private String name;
private String owner;
private int tenantId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -21,9 +21,11 @@ package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
//TODO :
@ -38,6 +40,7 @@ public class PIPDevice {
private String latitude;
private String longitude;
private Timestamp timestamp;
private List<DeviceGroup> deviceGroups;
/*This will be used to record attributes to which would come from other PDPs*/
Map<String, Object> attributes;
@ -121,4 +124,12 @@ public class PIPDevice {
public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public List<DeviceGroup> getDeviceGroups() {
return deviceGroups;
}
public void setDeviceGroups(List<DeviceGroup> deviceGroups) {
this.deviceGroups = deviceGroups;
}
}

@ -63,6 +63,11 @@ public class Policy implements Comparable<Policy>, Serializable {
private Map<String, Object> attributes;
/*This will keep the list of groups to which the policy will be applied. */
private List<DeviceGroupWrapper> deviceGroups;
@XmlElement
public int getId() {
return id;
@ -217,6 +222,15 @@ public class Policy implements Comparable<Policy>, Serializable {
}
@XmlElement
public List<DeviceGroupWrapper> getDeviceGroups() {
return deviceGroups;
}
public void setDeviceGroups(List<DeviceGroupWrapper> deviceGroups) {
this.deviceGroups = deviceGroups;
}
@Override
public int compareTo(Policy o) {
if (this.priorityId == o.priorityId)

@ -19,12 +19,17 @@
package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import java.util.List;
import java.util.Map;
public interface PolicyFilter {
List<Policy> filterActivePolicies(List<Policy> policies);
List<Policy> filterDeviceGroupsPolicies(Map<Integer, DeviceGroup> groupMap, List<Policy> policies);
List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies);
List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> policies);

@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyCriterion;
@ -41,7 +42,7 @@ public interface PolicyDAO {
*/
Policy addPolicyToRole(List<String> roleNames, Policy policy) throws PolicyManagerDAOException;
Policy updateRolesOfPolicy(List<String> rolesToAdd, Policy policy) throws PolicyManagerDAOException;
Policy updateRolesOfPolicy(List<String> rolesToAdd, Policy policy) throws PolicyManagerDAOException;
/**
* This method is used to add/update the users associated with the policy.
@ -56,6 +57,10 @@ public interface PolicyDAO {
Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException;
void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException;
List<DeviceGroupWrapper> getDeviceGroupsOfPolicy(int policyId) throws PolicyManagerDAOException;
boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagerDAOException;
void activatePolicy(int policyId) throws PolicyManagerDAOException;

@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyCriterion;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
@ -272,6 +273,64 @@ public class PolicyDAOImpl implements PolicyDAO {
return policy;
}
@Override
public void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
List<DeviceGroupWrapper> deviceGroupWrappers = policy.getDeviceGroups();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "INSERT INTO DM_DEVICE_GROUP_POLICY (DEVICE_GROUP_ID, POLICY_ID, TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(query);
for (DeviceGroupWrapper wrapper : deviceGroupWrappers) {
stmt.setInt(1, wrapper.getId());
stmt.setInt(2, policy.getId());
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while adding the device group details to the policy.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public List<DeviceGroupWrapper> getDeviceGroupsOfPolicy(int policyId) throws PolicyManagerDAOException {
List<DeviceGroupWrapper> deviceGroupWrappers = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "SELECT * FROM DM_DEVICE_GROUP_POLICY WHERE TENANT_ID = ? AND POLICY_ID = ?";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId);
stmt.setInt(2, policyId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
DeviceGroupWrapper dgw = new DeviceGroupWrapper();
dgw.setId(resultSet.getInt("DEVICE_GROUP_ID"));
dgw.setTenantId(tenantId);
deviceGroupWrappers.add(dgw);
}
} catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while reading the device groups form database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupWrappers;
}
@Override
public boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagerDAOException {
Connection conn;
@ -442,7 +501,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_CRITERIA (TENANT_ID, NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(query, new String[] {"id"});
stmt = conn.prepareStatement(query, new String[]{"id"});
stmt.setInt(1, tenantId);
stmt.setString(2, criteria.getName());
stmt.executeUpdate();
@ -622,7 +681,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_CRITERIA (CRITERIA_ID, POLICY_ID) VALUES (?, ?)";
stmt = conn.prepareStatement(query, new String[] {"id"});
stmt = conn.prepareStatement(query, new String[]{"id"});
List<PolicyCriterion> criteria = policy.getPolicyCriterias();
for (PolicyCriterion criterion : criteria) {
@ -1322,6 +1381,12 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(1, policyId);
stmt.executeUpdate();
String deleteDeviceGroups = "DELETE FROM DM_DEVICE_GROUP_POLICY WHERE POLICY_ID = ?";
stmt = conn.prepareStatement(deleteDeviceGroups);
stmt.setInt(1, policyId);
stmt.executeUpdate();
if (log.isDebugEnabled()) {
log.debug("Policy (" + policyId + ") related configs deleted from database.");
}
@ -1348,7 +1413,7 @@ public class PolicyDAOImpl implements PolicyDAO {
conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
"UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, new String[] {"id"});
stmt = conn.prepareStatement(query, new String[]{"id"});
stmt.setString(1, policy.getPolicyName());
stmt.setInt(2, policy.getProfile().getProfileId());

@ -21,12 +21,16 @@ package org.wso2.carbon.policy.mgt.core.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper;
import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyFilter;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PolicyFilterImpl implements PolicyFilter {
@ -59,6 +63,29 @@ public class PolicyFilterImpl implements PolicyFilter {
return temp;
}
@Override
public List<Policy> filterDeviceGroupsPolicies(Map<Integer, DeviceGroup> groupMap, List<Policy> policies) {
List<Policy> temp = new ArrayList<Policy>();
Map<Integer, Policy> policyMap = new HashMap<>();
for (Policy policy : policies) {
List<DeviceGroupWrapper> wrappers = policy.getDeviceGroups();
if (PolicyManagementConstants.ANY.equalsIgnoreCase(wrappers.get(0).getName())) {
temp.add(policy);
policyMap.put(policy.getId(), policy);
continue;
} else {
for (DeviceGroupWrapper deviceGroupWrapper : wrappers) {
if (groupMap.containsKey(deviceGroupWrapper.getId()) && policyMap.containsKey(policy.getId())) {
temp.add(policy);
policyMap.put(policy.getId(), policy);
}
}
}
}
return temp;
}
@Override
public List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies) {
@ -68,7 +95,7 @@ public class PolicyFilterImpl implements PolicyFilter {
log.debug("Names of policy went in to filterRolesBasedPolicies : " + policy.getPolicyName());
}
log.debug("Roles passed to match.");
for(String role : roles){
for (String role : roles) {
log.debug("Role name passed : " + role);
}
}
@ -79,7 +106,7 @@ public class PolicyFilterImpl implements PolicyFilter {
List<String> tempRoles = policy.getRoles();
if (tempRoles.isEmpty()) {
if(log.isDebugEnabled()) {
if (log.isDebugEnabled()) {
log.debug("Roles list is empty.");
}
temp.add(policy);

@ -24,10 +24,14 @@ import org.wso2.carbon.context.CarbonContext;
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.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
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.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
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;
@ -62,41 +66,35 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
public PIPDevice getDeviceData(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
PIPDevice pipDevice = new PIPDevice();
Device device;
DeviceType deviceType = new DeviceType();
deviceType.setName(deviceIdentifier.getType());
DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl();
GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl();
try {
device = deviceManagementService.getDevice(deviceIdentifier);
Thread.currentThread();
if (device != null) {
/*deviceManagementService.getDeviceType(deviceIdentifier.getType());*/
pipDevice.setDevice(device);
pipDevice.setRoles(getRoleOfDevice(device));
pipDevice.setDeviceType(deviceType);
pipDevice.setDeviceIdentifier(deviceIdentifier);
pipDevice.setUserId(device.getEnrolmentInfo().getOwner());
pipDevice.setOwnershipType(device.getEnrolmentInfo().getOwnership().toString());
pipDevice.setDeviceGroups(groupManagementProviderService.getGroups(pipDevice.getDeviceIdentifier()));
// TODO : Find a way to retrieve the timestamp and location (lat, long) of the device
// 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);
throw new PolicyManagementException(msg, e);
} catch (GroupManagementException e) {
String msg = "Error occurred when retrieving the data related to device groups from the database.";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
return pipDevice;
}
@ -128,6 +126,9 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) {
policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies);
}
if (pipDevice.getDeviceGroups() != null && !pipDevice.getDeviceGroups().isEmpty()) {
}
if (log.isDebugEnabled()) {
log.debug("No of policies selected for the device type : " + pipDevice.getDeviceType().getName() + " : " +

@ -24,11 +24,15 @@ import org.wso2.carbon.context.CarbonContext;
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.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
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.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl;
import org.wso2.carbon.policy.mgt.core.dao.*;
@ -86,6 +90,10 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyToDevice(policy.getDevices(), policy);
}
if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) {
policyDAO.addDeviceGroupsToPolicy(policy);
}
if (policy.getPolicyCriterias() != null) {
List<PolicyCriterion> criteria = policy.getPolicyCriterias();
for (PolicyCriterion criterion : criteria) {
@ -164,8 +172,8 @@ public class PolicyManagerImpl implements PolicyManager {
}
// Check for the features to delete
for(ProfileFeature feature : existingProfileFeaturesList) {
if(!updateDFes.contains(feature.getFeatureCode())){
for (ProfileFeature feature : existingProfileFeaturesList) {
if (!updateDFes.contains(feature.getFeatureCode())) {
feturesToDelete.add(feature);
}
}
@ -191,9 +199,9 @@ public class PolicyManagerImpl implements PolicyManager {
featureDAO.addProfileFeatures(newFeaturesList, profileId);
}
if(!feturesToDelete.isEmpty()){
if (!feturesToDelete.isEmpty()) {
for (ProfileFeature pf : feturesToDelete)
featureDAO.deleteProfileFeatures(pf.getId());
featureDAO.deleteProfileFeatures(pf.getId());
}
policyDAO.deleteCriteriaAndDeviceRelatedConfigs(policy.getId());
@ -211,6 +219,10 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyToDevice(policy.getDevices(), previousPolicy);
}
if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) {
policyDAO.addDeviceGroupsToPolicy(policy);
}
if (policy.getPolicyCriterias() != null) {
List<PolicyCriterion> criteria = policy.getPolicyCriterias();
for (PolicyCriterion criterion : criteria) {
@ -593,12 +605,21 @@ public class PolicyManagerImpl implements PolicyManager {
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);
} catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting all the policies.", e);
} catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
} catch (GroupManagementException e) {
throw new PolicyManagementException("Error occurred while getting device groups.", e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
@ -990,4 +1011,14 @@ public class PolicyManagerImpl implements PolicyManager {
}
}
private List<DeviceGroupWrapper> getDeviceGroupNames(List<DeviceGroupWrapper> groupWrappers) throws GroupManagementException {
GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl();
for (DeviceGroupWrapper wrapper : groupWrappers) {
DeviceGroup deviceGroup = groupManagementProviderService.getGroup(wrapper.getId());
wrapper.setName(deviceGroup.getName());
wrapper.setOwner(deviceGroup.getOwner());
}
return groupWrappers;
}
}

@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
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.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
@ -224,4 +225,13 @@ public class PolicyManagerUtil {
return monitoringFrequency;
}
public static Map<Integer, DeviceGroup> convertDeviceGroupMap(List<DeviceGroup> deviceGroups) {
Map<Integer, DeviceGroup> groupMap = new HashMap<>();
for (DeviceGroup dg: deviceGroups){
groupMap.put(dg.getId(), dg);
}
return groupMap;
}
}

@ -30,6 +30,7 @@ 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.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
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;
@ -76,6 +77,7 @@ public abstract class BasePolicyManagementDAOTest {
DeviceManagementDAOFactory.init(dataSource);
PolicyManagementDAOFactory.init(dataSource);
OperationManagementDAOFactory.init(dataSource);
GroupManagementDAOFactory.init(dataSource);
}
public void initiatePrivilegedCaronContext() throws Exception {

@ -6,38 +6,49 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL,
DESCRIPTION TEXT NULL DEFAULT NULL,
NAME VARCHAR(100) NULL DEFAULT NULL,
DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL,
OWNERSHIP VARCHAR(45) NULL DEFAULT NULL,
STATUS VARCHAR(15) NULL DEFAULT NULL,
DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL,
OWNER VARCHAR(45) NULL DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
NAME VARCHAR(100) DEFAULT NULL,
DEVICE_TYPE_ID INT(11) DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID )
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) NULL DEFAULT NULL,
STATUS VARCHAR(50) NULL,
DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
GROUP_ID INTEGER DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_OPERATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
TYPE VARCHAR(50) NOT NULL,
@ -81,6 +92,20 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION (
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
ID INTEGER AUTO_INCREMENT NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
@ -95,29 +120,17 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
OPERATION_RESPONSE BLOB DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
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
);
--- POLICY RELATED TABLES ----
-- POLICY RELATED TABLES --
CREATE TABLE IF NOT EXISTS DM_PROFILE (
ID INT NOT NULL AUTO_INCREMENT ,
@ -140,7 +153,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE (
CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) NULL DEFAULT NULL ,
NAME VARCHAR(45) DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL ,
@ -206,7 +219,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(30) NOT NULL,
FEATURE_CODE VARCHAR(100) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL ,
CONTENT BLOB NULL DEFAULT NULL,
@ -250,8 +263,8 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL,
ID INT NOT NULL AUTO_INCREMENT ,
DEVICE_ID INT NOT NULL ,
ENROLMENT_ID INT(11) NOT NULL,
POLICY_ID INT NOT NULL ,
POLICY_CONTENT BLOB NULL ,
@ -296,8 +309,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
POLICY_CRITERION_ID INT NOT NULL,
@ -312,8 +323,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL,
@ -325,13 +334,16 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
LAST_REQUESTED_TIME TIMESTAMP NULL,
LAST_FAILED_TIME TIMESTAMP NULL,
ATTEMPTS INT NULL,
PRIMARY KEY (ID),
UNIQUE INDEX DEVICE_ID_UNIQUE (DEVICE_ID ASC),
CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY
FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
PRIMARY KEY (ID)
);
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)
);
@ -339,7 +351,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ID INT NOT NULL AUTO_INCREMENT,
COMPLIANCE_STATUS_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
FEATURE_CODE VARCHAR(15) NOT NULL,
FEATURE_CODE VARCHAR(100) NOT NULL,
STATUS INT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS
@ -349,17 +361,177 @@ 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)
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_APPLICATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
NAME VARCHAR(150) NOT NULL,
APP_IDENTIFIER VARCHAR(150) NOT NULL,
PLATFORM VARCHAR(50) DEFAULT NULL,
CATEGORY VARCHAR(50) NULL,
VERSION VARCHAR(50) NULL,
TYPE VARCHAR(50) NULL,
LOCATION_URL VARCHAR(100) DEFAULT NULL,
IMAGE_URL VARCHAR(100) DEFAULT NULL,
APP_PROPERTIES BLOB NULL,
MEMORY_USAGE INTEGER(10) NULL,
TENANT_ID INTEGER NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
APPLICATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES
DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- POLICY RELATED TABLES FINISHED --
-- NOTIFICATION TABLE --
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(100) NULL,
PRIMARY KEY (NOTIFICATION_ID),
CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES
DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- NOTIFICATION TABLE END --
DROP TABLE IF EXISTS DM_DEVICE_INFO;
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT NULL,
KEY_FIELD VARCHAR(45) NULL,
VALUE_FIELD VARCHAR(100) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_INFO_DEVICE
FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INT NULL,
LATITUDE DOUBLE NULL,
LONGITUDE DOUBLE NULL,
STREET1 VARCHAR(45) NULL,
STREET2 VARCHAR(45) NULL,
CITY VARCHAR(45) NULL,
ZIP VARCHAR(10) NULL,
STATE VARCHAR(45) NULL,
COUNTRY VARCHAR(45) NULL,
PRIMARY KEY (ID),
CONSTRAINT DM_DEVICE_LOCATION_DEVICE
FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL,
DEVICE_MODEL VARCHAR(45) NULL,
VENDOR VARCHAR(45) NULL,
OS_VERSION VARCHAR(45) NULL,
BATTERY_LEVEL DECIMAL(4) NULL,
INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL,
INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL,
EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL,
EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL,
CONNECTION_TYPE VARCHAR(10) NULL,
SSID VARCHAR(45) NULL,
CPU_USAGE DECIMAL(5) NULL,
TOTAL_RAM_MEMORY DECIMAL(30,3) NULL,
AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL,
PLUGGED_IN INT(1) NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- POLICY AND DEVICE GROUP MAPPING --
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_GROUP_ID INT NOT NULL,
POLICY_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
FOREIGN KEY (DEVICE_GROUP_ID)
REFERENCES DM_GROUP (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
REFERENCES DM_POLICY (ID , ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
-- TO:DO - Remove this INSERT sql statement.
--Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android');
--Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (2, 'ios');
-- END OF POLICY AND DEVICE GROUP MAPPING --
CREATE VIEW DEVICES_VIEW_1 AS
SELECT
DEVICE_INFO.DEVICE_ID,
DEVICE_INFO.PLATFORM,
DEVICE_INFO.OWNERSHIP,
DEVICE_INFO.CONNECTIVITY_STATUS,
IFNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID,
IFNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT,
DEVICE_INFO.TENANT_ID
FROM
(SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE_TYPE.NAME AS PLATFORM,
DM_ENROLMENT.OWNERSHIP AS OWNERSHIP,
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
DM_DEVICE.TENANT_ID AS TENANT_ID
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
LEFT JOIN
(SELECT
DEVICE_ID,
POLICY_ID,
STATUS AS IS_COMPLIANT
FROM
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_INFO.DEVICE_ID;

@ -379,6 +379,58 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING (
-- END OF POLICY RELATED TABLES --
-- DEVICE GROUP TABLES --
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
)ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
GROUP_ID INTEGER DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;
-- END OF DEVICE GROUP TABLES --
-- POLICY AND DEVICE GROUP MAPPING --
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
ID INT NOT NULL AUTO_INCREMENT,
DEVICE_GROUP_ID INT NOT NULL,
POLICY_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
FOREIGN KEY (DEVICE_GROUP_ID)
REFERENCES DM_GROUP (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
REFERENCES DM_POLICY (ID , ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)ENGINE = InnoDB;
-- END OF POLICY AND DEVICE GROUP MAPPING --
-- NOTIFICATION TABLES --
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (

Loading…
Cancel
Save