Fixed merge conflicts

revert-70aa11f8
mharindu 9 years ago
commit 6f8bb64e1c

@ -18,30 +18,49 @@
package org.wso2.carbon.apimgt.webapp.publisher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils;
import javax.servlet.ServletContext;
import java.util.*;
public class APIPublisherUtil {
private static final Log log = LogFactory.getLog(APIPublisherUtil.class);
private static final String DEFAULT_API_VERSION = "1.0.0";
private static final String API_VERSION_PARAM="{version}";
private static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox";
public static final String API_VERSION_PARAM = "{version}";
public static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox";
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
private static final String PARAM_MANAGED_API_NAME = "managed-api-name";
private static final String PARAM_MANAGED_API_VERSION = "managed-api-version";
private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context";
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint";
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner";
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports";
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
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);
@ -50,12 +69,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);
@ -66,8 +87,10 @@ public class APIPublisherUtil {
environments.add(API_PUBLISH_ENVIRONMENT);
api.setEnvironments(environments);
Set<Tier> tiers = new HashSet<>();
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);
@ -79,6 +102,7 @@ public class APIPublisherUtil {
String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig);
if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) {
@ -142,14 +166,15 @@ public class APIPublisherUtil {
}
/**
* When an input is having '@',replace it with '-AT-'
* [This is required to persist API data in registry,as registry paths don't allow '@' sign.]
* When an input is having '@',replace it with '-AT-'
* [This is required to persist API data in registry,as registry paths don't allow '@' sign.]
*
* @param input inputString
* @return String modifiedString
*/
private static String replaceEmailDomain(String input){
if(input!=null&& input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR) ){
input=input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR,APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
private static String replaceEmailDomain(String input) {
if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR)) {
input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR, APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
}
return input;
}
@ -164,13 +189,130 @@ public class APIPublisherUtil {
private static String checkAndSetVersionParam(String 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.
if(!context.contains(API_VERSION_PARAM)){
if(!context.endsWith("/")){
if (!context.contains(API_VERSION_PARAM)) {
if (!context.endsWith("/")) {
context = context + "/";
}
context = context +API_VERSION_PARAM;
context = context + API_VERSION_PARAM;
}
return context;
}
/**
* Build the API Configuration to be passed to APIM, from a given list of URL templates
*
* @param servletContext
* @return
*/
public static APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apidef) {
APIConfig apiConfig = new APIConfig();
String name = apidef.getName();
if (name == null || name.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("API Name not set in @API Annotation");
}
name = servletContext.getServletContextName();
}
apiConfig.setName(name);
String version = apidef.getVersion();
if (version == null || version.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Version not set in @API Annotation'");
}
version = API_CONFIG_DEFAULT_VERSION;
}
apiConfig.setVersion(version);
String context = apidef.getContext();
if (context == null || context.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Context not set in @API Annotation'");
}
context = servletContext.getContextPath();
}
apiConfig.setContext(context);
String[] tags = apidef.getTags();
if (tags == null || tags.length == 0) {
if (log.isDebugEnabled()) {
log.debug("'API tag not set in @API Annotation'");
}
} else {
apiConfig.setTags(tags);
}
String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN);
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured");
}
String endpointContext = servletContext.getContextPath();
endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
}
apiConfig.setEndpoint(endpoint);
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-owner' attribute is not configured");
}
}
apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured;
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which is 'https'");
}
transports = "https";
}
apiConfig.setTransports(transports);
String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty())
&& Boolean.parseBoolean(sharingValueParam));
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
for (APIResource apiResource : apidef.getResources()) {
URITemplate template = new URITemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());
template.setScope(apiResource.getScope());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
}

@ -24,38 +24,24 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.*;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil;
import org.wso2.carbon.base.MultitenantConstants;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@SuppressWarnings("unused")
public class APIPublisherLifecycleListener implements LifecycleListener {
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
private static final String PARAM_MANAGED_API_NAME = "managed-api-name";
private static final String PARAM_MANAGED_API_VERSION = "managed-api-version";
private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context";
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint";
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner";
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports";
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
@ -70,13 +56,21 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil.
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext, annotatedAPIClasses);
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext,
annotatedAPIClasses);
for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition);
APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
try {
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain());
boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId);
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().
getTenantId(apiConfig.getTenantDomain());
boolean isTenantActive = APIPublisherDataHolder.getInstance().
getTenantManager().isTenantActive(tenantId);
if (isTenantActive) {
apiConfig.init();
API api = APIPublisherUtil.getAPI(apiConfig);
@ -88,7 +82,8 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
}
apiPublisherService.publishAPI(api);
} else {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp");
log.error("No tenant [" + apiConfig.getTenantDomain() + "] " +
"found when publishing the Web app");
}
} catch (Throwable e) {
log.error("Error occurred while publishing API '" + apiConfig.getName() +
@ -105,127 +100,9 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
}
}
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes
private List<APIResourceConfiguration> mergeAPIDefinitions(List<APIResourceConfiguration> inputList) {
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two
// classes
return null;
}
/**
* Build the API Configuration to be passed to APIM, from a given list of URL templates
*
* @param servletContext
* @return
*/
private APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apidef) {
APIConfig apiConfig = new APIConfig();
String name = apidef.getName();
if (name == null || name.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("API Name not set in @API Annotation");
}
name = servletContext.getServletContextName();
}
apiConfig.setName(name);
String version = apidef.getVersion();
if (version == null || version.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Version not set in @API Annotation'");
}
version = API_CONFIG_DEFAULT_VERSION;
}
apiConfig.setVersion(version);
String context = apidef.getContext();
if (context == null || context.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Context not set in @API Annotation'");
}
context = servletContext.getContextPath();
}
apiConfig.setContext(context);
String[] tags = apidef.getTags();
if (tags == null || tags.length == 0) {
if (log.isDebugEnabled()) {
log.debug("'API tag not set in @API Annotation'");
}
} else {
apiConfig.setTags(tags);
}
String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN);
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured");
}
String endpointContext = servletContext.getContextPath();
endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
}
apiConfig.setEndpoint(endpoint);
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-owner' attribute is not configured");
}
}
apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured;
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which is 'https'");
}
transports = "https";
}
apiConfig.setTransports(transports);
String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty()) && Boolean.parseBoolean(
sharingValueParam));
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
Scope scope;
for (APIResource apiResource : apidef.getResources()) {
URITemplate template = new URITemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());;
template.setScope(apiResource.getScope());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
}

@ -54,17 +54,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;
@ -118,38 +119,23 @@ public class AnnotationUtil {
APIResourceConfiguration apiResourceConfig = null;
try {
clazz = classLoader.loadClass(className);
Class<API> apiClazz = (Class<API>)
classLoader.loadClass(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());
@ -188,7 +174,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) {
@ -207,30 +231,17 @@ public class AnnotationUtil {
Annotation[] annotations = method.getDeclaredAnnotations();
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);
}
processHTTPMethodAnnotation(resource, annotations[i]);
if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) {
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(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());
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));
@ -254,6 +265,34 @@ public class AnnotationUtil {
return resourceList;
}
/**
* 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("/")) {

@ -18,6 +18,9 @@
package org.wso2.carbon.device.mgt.analytics.dashboard;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.Map;
/**
@ -26,7 +29,7 @@ import java.util.Map;
public interface GadgetDataService {
@SuppressWarnings("unused")
int getTotalDeviceCount(Map<String, Object> filters);
int getTotalDeviceCount();
@SuppressWarnings("unused")
int getActiveDeviceCount();
@ -44,12 +47,26 @@ public interface GadgetDataService {
int getUnmonitoredDeviceCount();
@SuppressWarnings("unused")
Map<String, Integer> getNonCompliantDeviceCountsByFeatures();
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest);
@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);
}

@ -18,6 +18,9 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List;
import java.util.Map;
@ -26,15 +29,9 @@ public interface GadgetDataServiceDAO {
/**
* Method to get total filtered device count from a particular tenant.
*
* @param filters List of filters to be applied in getting
* total filtered device count.
*
* @return Total filtered device count.
*/
int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
int getTotalDeviceCount() throws GadgetDataServiceDAOException;
int getActiveDeviceCount() throws GadgetDataServiceDAOException;
@ -50,9 +47,6 @@ public interface GadgetDataServiceDAO {
@SuppressWarnings("unused")
int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException;
/**
* Method to get unmonitored device count.
*
@ -61,22 +55,36 @@ public interface GadgetDataServiceDAO {
@SuppressWarnings("unused")
int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
}

@ -21,6 +21,8 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
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.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.Connection;
@ -37,122 +39,141 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class);
@Override
public int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCount(filteringViewID, filters);
}
@Override
public int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCount(filteringViewID, filters);
public int getTotalDeviceCount() throws GadgetDataServiceDAOException {
return this.getDeviceCount(null);
}
@Override
public int getActiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "ACTIVE");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getInactiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "INACTIVE");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getRemovedDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "REMOVED");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("IS_COMPLIANT", 0);
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException {
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredNonCompliantDeviceCountsByFeatures = new HashMap<>();
List<Map<String, Object>> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
int totalRecordsCount = 0;
try {
con = this.getConnection();
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE";
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, paginationRequest.getStartIndex());
stmt.setInt(3, paginationRequest.getRowCount());
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredNonCompliantDeviceCountByFeature;
while (rs.next()) {
filteredNonCompliantDeviceCountByFeature = new HashMap<>();
filteredNonCompliantDeviceCountByFeature.put("FEATURE_CODE", rs.getString("FEATURE_CODE"));
filteredNonCompliantDeviceCountByFeature.put("DEVICE_COUNT", rs.getInt("DEVICE_COUNT"));
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
}
// fetching total records count
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?)";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredNonCompliantDeviceCountsByFeatures.
put(rs.getString("FEATURE_CODE"), rs.getInt("DEVICE_COUNT"));
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredNonCompliantDeviceCountsByFeatures;
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
paginationResult.setRecordsTotal(totalRecordsCount);
return paginationResult;
}
@Override
public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("POLICY_ID", -1);
return this.getDeviceCount(filteringViewID, filters);
}
@Override
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCountsByPlatforms(filteringViewID, filters);
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCountsByPlatforms(filteringViewID, filters);
}
@Override
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters);
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDevicesWithDetails(filteringViewID, filters);
}
@Override
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDevicesWithDetails(filteringViewID, filters);
public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
int filteredDeviceCount = 0;
try {
con = this.getConnection();
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
sql = sql + " AND " + column + " = ?";
}
}
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
if (filters != null && filters.values().size() > 0) {
int i = 2;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCount;
}
private int getDeviceCount(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -160,13 +181,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
int filteredDeviceCount = 0;
try {
con = this.getConnection();
String sql;
if (filteringViewID == 1) {
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
} else {
// if filteringViewID == 2
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?";
}
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns
if (filters != null && filters.size() > 0) {
@ -177,8 +192,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 2;
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
@ -202,7 +218,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCount;
}
private Map<String, Integer> getDeviceCountsByPlatforms(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -218,14 +234,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
if (filteringViewID == 1) {
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
} else {
// if filteringViewID == 2
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
}
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
@ -254,12 +264,12 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCountsByPlatforms;
}
private Map<String, Integer> getDeviceCountsByOwnershipTypes(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
@ -270,14 +280,55 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
if (filteringViewID == 1) {
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
} else {
// if filteringViewID == 2
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByPlatforms;
}
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
@ -306,7 +357,54 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCountsByOwnershipTypes;
}
private List<Map<String, Object>> getDevicesWithDetails(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY OWNERSHIP";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByOwnershipTypes;
}
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -316,12 +414,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
try {
con = this.getConnection();
String sql;
if (filteringViewID == 1) {
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
} else {
// if filteringViewID == 2
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?";
}
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
@ -361,6 +454,58 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDevicesWithDetails;
}
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Object> filteredDeviceWithDetails = new HashMap<>();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
try {
con = this.getConnection();
String sql;
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
sql = sql + " AND " + column + " = ?";
}
}
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDevicesWithDetails;
}
private Connection getConnection() throws SQLException {
return GadgetDataServiceDAOFactory.getConnection();
}

@ -23,6 +23,8 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.sql.SQLException;
import java.util.Map;
@ -36,12 +38,11 @@ class GadgetDataServiceImpl implements GadgetDataService {
private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class);
@Override
public int getTotalDeviceCount(Map<String, Object> filters) {
public int getTotalDeviceCount() {
int totalDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
totalDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getTotalDeviceCount(filters);
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
totalDeviceCount = -1;
return totalDeviceCount;
@ -56,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;
@ -72,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;
@ -88,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;
@ -104,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;
@ -120,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;
@ -132,18 +128,49 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() {
Map<String, Integer> nonCompliantDeviceCountsByFeatures = null;
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) {
PaginationResult paginationResult = null;
try {
GadgetDataServiceDAOFactory.openConnection();
nonCompliantDeviceCountsByFeatures =
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCountsByFeatures();
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getNonCompliantDeviceCountsByFeatures(paginationRequest);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return nonCompliantDeviceCountsByFeatures;
return paginationResult;
}
@Override
public int getDeviceCount(Map<String, Object> filters) {
int deviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
deviceCount = -1;
return deviceCount;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
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
@ -151,8 +178,8 @@ class GadgetDataServiceImpl implements GadgetDataService {
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 {
@ -161,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 {
@ -176,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 {

@ -258,32 +258,34 @@ deviceModule = function () {
};
// Refactored methods
publicMethods.getOwnDevicesCount = function () {
publicMethods.getDevicesCount = function () {
var carbonUser = session.get(constants.USER_SESSION_KEY);
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username
+ "/count";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
};
publicMethods.getAllDevicesCount = function () {
var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count";
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
if (carbonUser) {
var userModule = require("/app/modules/user.js").userModule;
var uiPermissions = userModule.getUIPermissions();
var url;
if (uiPermissions.LIST_DEVICES) {
url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count";
} else if (uiPermissions.LIST_OWN_DEVICES) {
url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username
+ "/count";
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
return responsePayload;
},
function (responsePayload) {
log.error(responsePayload);
return -1;
}
);
} else {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
};
publicMethods.getDeviceTypes = function () {

@ -38,12 +38,14 @@ var groupModule = {};
endPoint = groupServiceEndpoint + "/count";
} else if (permissions.LIST_GROUPS) {
endPoint = groupServiceEndpoint + "/user/" + user.username + "/count";
} else {
log.error("Access denied for user: " + carbonUser.username);
return -1;
}
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload;
}
,
},
function (responsePayload) {
log.error(responsePayload);
return -1;
@ -56,8 +58,7 @@ var groupModule = {};
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload;
}
,
},
function (responsePayload) {
log.error(responsePayload);
return -1;

@ -653,6 +653,9 @@ var userModule = function () {
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/list")) {
permissions["LIST_POLICIES"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/add")) {
permissions["ADD_DEVICE"] = true;
}
if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/add")) {
permissions["ADD_GROUP"] = true;
}

@ -1,42 +0,0 @@
{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}}
{{unit "cdmf.unit.ui.content.title" pageHeader=title}}
{{#zone "breadcrumbs"}}
<li>
<a href="{{@app.context}}/">
<i class="icon fw fw-home"></i>
</a>
</li>
{{#if groupName}}
<li>
<a href="{{@app.context}}/groups">
Groups
</a>
</li>
<li>
<a href="{{@app.context}}/devices?groupId={{groupId}}&groupName={{groupName}}">
{{groupName}}
</a>
</li>
{{else}}
<li>
<a href="{{@app.context}}/devices">
Devices
</a>
</li>
<li>
<a href="{{@app.context}}/device/{{deviceType}}?id={{deviceId}}">
{{deviceName}}
</a>
</li>
{{/if}}
<li>
<a href="#">
Analytics
</a>
</li>
{{/zone}}
{{#zone "content"}}
{{unit "cdmf.unit.analytics"}}
{{/zone}}

@ -1,39 +0,0 @@
/*
* 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.
*/
function onRequest(context) {
var groupName = request.getParameter("groupName");
var groupId = request.getParameter("groupId");
var deviceName = request.getParameter("deviceName");
var deviceId = request.getParameter("deviceId");
var deviceType = request.getParameter("deviceType");
var title = "Analytics";
if (groupName) {
title = "Group " + title;
} else {
title = "Device " + title;
}
return {
"title": title,
"groupName": groupName,
"groupId": groupId,
"deviceName": deviceName,
"deviceId": deviceId,
"deviceType": deviceType
};
}

@ -35,7 +35,7 @@ function onRequest(context) {
var groupModule = require("/app/modules/group.js").groupModule;
var policyModule = require("/app/modules/policy.js").policyModule;
page.device_count = deviceModule.getAllDevicesCount();
page.device_count = deviceModule.getDevicesCount();
page.group_count = groupModule.getGroupCount();
page.user_count = userModule.getUsers()["content"].length;
page.policy_count = policyModule.getAllPolicies()["content"].length;

@ -50,7 +50,7 @@
<div class=" margin-top-double">
<div class="row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-3 margin-top-double">
<h1 class="grey ">{{deviceType}} Analytics</h1>
<h1 class="grey ">{{deviceName}} Analytics</h1>
</div>
<div id="rangeSliderWrapper" class="pull-right col-lg-9">
<div id="dateRangePickerContainer">

@ -17,19 +17,35 @@
*/
function onRequest(context) {
context.handlebars.registerHelper('equal', function (lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if (lvalue != rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
var deviceType = context.uriParams.deviceType;
return {
"deviceAnalyticsViewUnitName": "cdmf.unit.device.type." + deviceType + ".analytics-view",
"deviceType": deviceType
};
}
var utility = require("/app/modules/utility.js").utility;
context.handlebars.registerHelper('equal', function (lvalue, rvalue, options) {
if (arguments.length < 3) {
throw new Error("Handlebars Helper equal needs 2 parameters");
}
if (lvalue != rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
var groupName = request.getParameter("groupName");
var groupId = request.getParameter("groupId");
var deviceName = request.getParameter("deviceName");
var deviceId = request.getParameter("deviceId");
var deviceType = context.uriParams.deviceType;
var title = "Analytics";
if (groupName) {
title = "Group " + title;
} else {
title = "Device " + title;
}
return {
"deviceAnalyticsViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "analytics-view"),
"deviceType": deviceType,
"title": title,
"groupName": groupName,
"groupId": groupId,
"deviceName": deviceName,
"deviceId": deviceId
};
}

@ -1,5 +1,5 @@
{
"version": "1.0.0",
"uri": "/device/analytics/{deviceType}",
"layout": "cdmf.layout.default"
"version": "1.0.0",
"uri": "/device/{deviceType}/analytics",
"layout": "cdmf.layout.default"
}

@ -34,8 +34,9 @@ function onRequest(context) {
var currentUser = session.get(constants.USER_SESSION_KEY);
if (currentUser) {
page.permissions = {};
page.permissions.list = stringify(userModule.getUIPermissions());
if (userModule.isAuthorized("/permission/admin/device-mgt/user/devices/add")) {
var uiPermissions = userModule.getUIPermissions();
page.permissions.list = stringify(uiPermissions);
if (uiPermissions.ADD_DEVICE) {
page.permissions.enroll = true;
}
page.currentUser = currentUser;
@ -45,7 +46,7 @@ function onRequest(context) {
deviceCount = groupModule.getGroupDeviceCount(groupName, groupOwner);
page.groupOwner = groupOwner;
} else {
deviceCount = deviceModule.getOwnDevicesCount();
deviceCount = deviceModule.getDevicesCount();
}
if (deviceCount > 0) {
page.deviceCount = deviceCount;

@ -300,7 +300,7 @@ function loadDevices(searchType, searchParam){
html = '<a href="device/' + deviceType + '?id=' + deviceIdentifier + '" data-click-event="remove-form"' +
' class="btn padding-reduce-on-grid-view"><span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
'<i class="fw fw-view fw-stack-1x"></i></span><span class="hidden-xs hidden-on-grid-view">View</span></a>';
html += '<a href="analytics?deviceId=' + deviceIdentifier + '&deviceType=' + deviceType + '&deviceName=' + row.name + '" ' +
html += '<a href="device/' + deviceType + '/analytics?deviceId=' + deviceIdentifier + '&deviceName=' + row.name + '" ' +
'data-click-event="remove-form" class="btn padding-reduce-on-grid-view"><span class="fw-stack">' +
'<i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-statistics fw-stack-1x"></i></span>' +
'<span class="hidden-xs hidden-on-grid-view">Analytics</span>';
@ -309,6 +309,11 @@ function loadDevices(searchType, searchParam){
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
'<i class="fw fw-edit fw-stack-1x"></i></span>' +
'<span class="hidden-xs hidden-on-grid-view">Edit</span></a>';
html += '<a href="#" data-click-event="remove-form" class="btn padding-reduce-on-grid-view remove-device-link" ' +
'data-deviceid="' + deviceIdentifier + '" data-devicetype="' + deviceType + '" data-devicename="' + row.name + '">' +
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
'<i class="fw fw-delete fw-stack-1x"></i></span>' +
'<span class="hidden-xs hidden-on-grid-view">Delete</span>';
}
return html;
}}

@ -1,87 +0,0 @@
{{#each devices}}
{{deviceMap this}}
<tr data-type="selectable" data-deviceid="{{deviceIdentifier}}" data-devicetype="{{type}}">
<td class="remove-padding icon-only content-fill">
<div class="thumbnail icon">
<img class="square-element text fw "
src="{{../imageLocation}}{{type}}.type-view/images/thumb.png"/>
</div>
</td>
<td class="fade-edge" data-search="{{properties.DEVICE_MODEL}},{{properties.VENDOR}}"
data-display="{{properties.DEVICE_MODEL}}">
<h4 data-deviceid="{{deviceIdentifier}}">{{name}}</h4>
{{#if properties.VENDOR}}
<div>({{properties.VENDOR}} - {{properties.DEVICE_MODEL}})</div>
{{/if}}
</td>
<td class="fade-edge remove-padding-top" data-search="{{enrolmentInfo.owner}}"
data-display="{{enrolmentInfo.owner}}"
data-grid-label="Owner">{{enrolmentInfo.owner}}</td>
<td class="fade-edge remove-padding-top" data-search="{{enrolmentInfo.status}}"
data-display="{{enrolmentInfo.status}}" data-grid-label="Status">
{{#equal enrolmentInfo.status "ACTIVE"}}<span><i class="fw fw-ok icon-success"></i> Active</span>{{/equal}}
{{#equal enrolmentInfo.status "INACTIVE"}}<span><i
class="fw fw-warning icon-warning"></i> Inactive</span>{{/equal}}
{{#equal enrolmentInfo.status "BLOCKED"}}<span><i class="fw fw-remove icon-danger"></i> Blocked</span>{{/equal}}
{{#equal enrolmentInfo.status "REMOVED"}}<span><i class="fw fw-delete icon-danger"></i> Removed</span>{{/equal}}
</td>
<td class="fade-edge remove-padding-top" data-search="{{type}}" data-display="{{type}}"
data-grid-label="Type">{{type}}</td>
<td class="fade-edge remove-padding-top" data-search="{{enrolmentInfo.ownership}}"
data-display="{{enrolmentInfo.ownership}}"
data-grid-label="Ownership">{{enrolmentInfo.ownership}}</td>
<td class="text-right content-fill text-left-on-grid-view no-wrap">
{{#unequal enrolmentInfo.status "REMOVED"}}
<a href="device/{{type}}?id={{deviceIdentifier}}"
data-click-event="remove-form" class="btn padding-reduce-on-grid-view">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">View</span>
</a>
<a href="analytics?deviceId={{deviceIdentifier}}&deviceType={{type}}&deviceName={{name}}"
data-click-event="remove-form" class="btn padding-reduce-on-grid-view">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-statistics fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">Analytics</span>
</a>
{{#unless ../../isGroupView}}
<a href="#" data-click-event="remove-form"
class="btn padding-reduce-on-grid-view group-device-link"
data-deviceid="{{deviceIdentifier}}" data-devicetype="{{type}}"
data-devicename="{{name}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-grouping fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">Group</span>
</a>
{{/unless}}
<a href="#" data-click-event="remove-form"
class="btn padding-reduce-on-grid-view edit-device-link"
data-deviceid="{{deviceIdentifier}}" data-devicetype="{{type}}"
data-devicename="{{name}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-edit fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">Edit</span>
</a>
<a href="#" data-click-event="remove-form"
class="btn padding-reduce-on-grid-view remove-device-link"
data-deviceid="{{deviceIdentifier}}" data-devicetype="{{type}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-delete fw-stack-1x"></i>
</span>
<span class="hidden-xs hidden-on-grid-view">Delete</span>
</a>
{{/unequal}}
</td>
</tr>
{{/each}}

@ -1,48 +0,0 @@
{{#zone "topCss"}}
{{css "css/analytics.css"}}
{{css "css/daterangepicker.css"}}
{{css "css/graph.css"}}
{{/zone}}
<span id="request-group-id" data-groupid="{{groupId}}"></span>
<div class="container container-bg white-bg">
<div class=" margin-top-double">
<div class="row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-3 margin-top-double">
<h1 class="grey ">{{title}}</h1>
</div>
<div id="rangeSliderWrapper" class="pull-right col-lg-9">
<div id="dateRangePickerContainer">
<div class="btn-group" role="group">
<button id="hour-btn" type="button"
class="btn btn-default date-range">Hour
</button>
<button id="h12-btn" type="button"
class="btn btn-default date-range">12 Hours
</button>
<button id="h24-btn" type="button"
class="btn btn-default date-range">24 Hours
</button>
<button id="h48-btn" type="button"
class="btn btn-default date-range">48 Hours
</button>
<button id="date-range" type="button"
class="btn btn-default date-range last-child"
data-toggle="popup"
title="Click to set custom date range"></button>
</div>
</div>
</div>
</div>
<hr>
<div class="clear"></div>
<div id="div-chart">
</div>
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/d3.min.js"}}
{{js "js/rickshaw.min.js"}}
{{js "js/moment.min.js"}}
{{js "js/jquery.daterangepicker.js"}}
{{js "js/graph_util.js"}}
{{/zone}}

@ -1,35 +0,0 @@
/*
* 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.
*/
function onRequest(context) {
var groupId = request.getParameter("groupId");
var title;
if (groupId) {
title = request.getParameter("groupName") + " Group";
} else {
groupId = 0;
var deviceId = request.getParameter("deviceId");
var deviceType = request.getParameter("deviceType");
var deviceName = request.getParameter("deviceName");
//title = deviceModule.getDevice(deviceType, deviceId).name;
title = deviceName;
}
return {"title": title, "groupId": groupId};
}

@ -1,63 +0,0 @@
/*
* 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.
*/
#rangeSliderWrapper {
margin-top: 25px;
}
#chart {
display: inline-block;
}
#legend {
display: inline-block;
position: relative;
left: 8px;
}
#legend_container {
position: absolute;
right: 0;
bottom: 26px;
width: 0;
}
#chart_container {
float: left;
position: relative;
}
.ast-container {
padding-bottom: 30px;
}
.container {
width: auto;
}
.shrink {
margin-right: 20px;
margin-left: 20px;
}
.date-range{
border: 1px solid #ccc;
}
#dateRangePickerContainer button.active{
background-color: #e6e6e6 !important;
}

@ -1,348 +0,0 @@
/*
* 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.
*/
.date-picker {
width: 170px;
height: 25px;
padding: 0;
border: 0;
line-height: 25px;
padding-left: 10px;
font-size: 12px;
font-family: Arial;
font-weight: bold;
cursor: pointer;
color: #303030;
position: relative;
z-index: 2;
}
.date-picker-wrapper {
position: absolute;
z-index: 1;
border: 1px solid #bfbfbf;
background-color: #efefef;
width: 448px;
padding: 5px 12px;
font-size: 12px;
line-height: 20px;
color: #aaa;
font-family: Arial;
box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.5);
}
.date-picker-wrapper.single-date {
width: auto;
}
.date-picker-wrapper.no-shortcuts {
padding-bottom: 12px;
}
.date-picker-wrapper .footer {
display: none;
font-size: 11px;
padding-top: 3px;
}
.date-picker-wrapper b {
color: #666;
font-weight: 700;
}
.date-picker-wrapper a {
color: rgb(107, 180, 214);
text-decoration: underline;
}
.date-picker-wrapper .month-wrapper {
border: 1px solid #bfbfbf;
border-radius: 3px;
background-color: #fff;
padding: 5px;
cursor: default;
position: relative;
_overflow: hidden;
}
.date-picker-wrapper .month-wrapper table {
width: 190px;
float: left;
}
.date-picker-wrapper .month-wrapper table.month2 {
width: 190px;
float: right;
}
.date-picker-wrapper .month-wrapper table th,
.date-picker-wrapper .month-wrapper table td {
vertical-align: middle;
text-align: center;
line-height: 14px;
margin: 0px;
padding: 0px;
}
.date-picker-wrapper .month-wrapper table .day {
height: 19px;
line-height: 19px;
font-size: 12px;
margin-bottom: 1px;
color: #999;
cursor: default;
}
.date-picker-wrapper .month-wrapper table div.day.lastMonth,
.date-picker-wrapper .month-wrapper table div.day.nextMonth {
color: #999;
cursor: default;
}
.date-picker-wrapper .month-wrapper table .day.checked {
background-color: rgb(156, 219, 247);
}
.date-picker-wrapper .month-wrapper table .week-name {
height: 20px;
line-height: 20px;
font-weight: 100;
}
.date-picker-wrapper .month-wrapper table .day.has-tooltip {
cursor: help !important;
}
.date-picker-wrapper .month-wrapper table .day.toMonth.valid {
color: #333;
cursor: pointer;
}
.date-picker-wrapper .month-wrapper table .day.real-today {
background-color: rgb(255, 230, 132);
}
.date-picker-wrapper .month-wrapper table .day.real-today.checked {
background-color: rgb(112, 204, 213);
}
.date-picker-wrapper table .caption {
height: 40px;
}
.date-picker-wrapper table .caption .next,
.date-picker-wrapper table .caption .prev {
padding: 0 5px;
cursor: pointer;
}
.date-picker-wrapper table .caption .next:hover,
.date-picker-wrapper table .caption .prev:hover {
background-color: #ccc;
color: white;
}
.date-picker-wrapper .gap {
position: absolute;
display: none;
top: 0px;
left: 204px;
z-index: 1;
width: 15px;
height: 100%;
background-color: red;
font-size: 0;
line-height: 0;
}
.date-picker-wrapper .gap .gap-lines {
height: 100%;
overflow: hidden;
}
.date-picker-wrapper .gap .gap-line {
height: 15px;
width: 15px;
position: relative;
}
.date-picker-wrapper .gap .gap-line .gap-1 {
z-index: 1;
height: 0;
border-left: 8px solid white;
border-top: 8px solid #eee;
border-bottom: 8px solid #eee;
}
.date-picker-wrapper .gap .gap-line .gap-2 {
position: absolute;
right: 0;
top: 0px;
z-index: 2;
height: 0;
border-left: 8px solid transparent;
border-top: 8px solid white;
}
.date-picker-wrapper .gap .gap-line .gap-3 {
position: absolute;
right: 0;
top: 8px;
z-index: 2;
height: 0;
border-left: 8px solid transparent;
border-bottom: 8px solid white;
}
.date-picker-wrapper .gap .gap-top-mask {
width: 6px;
height: 1px;
position: absolute;
top: -1px;
left: 1px;
background-color: #eee;
z-index: 3;
}
.date-picker-wrapper .gap .gap-bottom-mask {
width: 6px;
height: 1px;
position: absolute;
bottom: -1px;
left: 7px;
background-color: #eee;
z-index: 3;
}
.date-picker-wrapper .selected-days {
display: none;
}
.date-picker-wrapper .drp_top-bar {
line-height: 40px;
height: 40px;
position: relative;
}
.date-picker-wrapper .drp_top-bar .error-top {
display: none;
}
.date-picker-wrapper .drp_top-bar .normal-top {
display: none;
}
.date-picker-wrapper .drp_top-bar .default-top {
display: block;
}
.date-picker-wrapper .drp_top-bar.error .default-top {
display: none;
}
.date-picker-wrapper .drp_top-bar.error .error-top {
display: block;
color: red;
}
.date-picker-wrapper .drp_top-bar.normal .default-top {
display: none;
}
.date-picker-wrapper .drp_top-bar.normal .normal-top {
display: block;
}
.date-picker-wrapper .drp_top-bar .apply-btn {
position: absolute;
right: 0px;
top: 6px;
padding: 3px 5px;
margin: 0;
font-size: 12px;
border-radius: 4px;
cursor: pointer;
color: #d9eef7;
border: solid 1px #0076a3;
background: #0095cd;
background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
background: -moz-linear-gradient(top, #00adee, #0078a5);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#0078a5');
color: white;
}
.date-picker-wrapper .drp_top-bar .apply-btn.disabled {
pointer-events: none;
color: #606060;
border: solid 1px #b7b7b7;
background: #fff;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed));
background: -moz-linear-gradient(top, #fff, #ededed);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed');
}
/*time styling*/
.time {
position: relative;
}
.time input[type=range] {
vertical-align: middle;
}
.time1, .time2 {
width: 180px;
padding: 0 5px;
text-align: center;
}
.time1 {
float: left;
}
.time2 {
float: right;
}
.hour, .minute {
text-align: left;
}
.hide {
display: none;
}
input.hour-range, input.minute-range {
width: 150px;
}
#dateRangePickerContainer .date-range, #dateRangePickerContainer .input-append {
background: none !important;
}
#date-range {
padding-right: 30px;
width: 300px;
height: 100%;
display: inline-block;
}
#dateRangePickerContainer {
float: right;
}

@ -1,463 +0,0 @@
/*
* 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.
*/
/* graph */
.rickshaw_graph {
position: relative;
}
.rickshaw_graph svg {
display: block;
overflow: hidden;
}
/* ticks */
.rickshaw_graph .x_tick {
position: absolute;
top: 0;
bottom: 0;
width: 0;
border-left: 1px dotted rgba(0, 0, 0, 0.2);
pointer-events: none;
}
.rickshaw_graph .x_tick .title {
position: absolute;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0.5;
white-space: nowrap;
margin-left: 3px;
bottom: -20px;
height: auto;
border-bottom: none;
}
/* annotations */
.rickshaw_annotation_timeline {
height: 1px;
border-top: 1px solid #e0e0e0;
margin-top: 10px;
position: relative;
}
.rickshaw_annotation_timeline .annotation {
position: absolute;
height: 6px;
width: 6px;
margin-left: -2px;
top: -3px;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.25);
}
.rickshaw_graph .annotation_line {
position: absolute;
top: 0;
bottom: -6px;
width: 0;
border-left: 2px solid rgba(0, 0, 0, 0.3);
display: none;
}
.rickshaw_graph .annotation_line.active {
display: block;
}
.rickshaw_graph .annotation_range {
background: rgba(0, 0, 0, 0.1);
display: none;
position: absolute;
top: 0;
bottom: -6px;
}
.rickshaw_graph .annotation_range.active {
display: block;
}
.rickshaw_graph .annotation_range.active.offscreen {
display: none;
}
.rickshaw_annotation_timeline .annotation .content {
background: white;
color: black;
opacity: 0.9;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
border-radius: 3px;
position: relative;
z-index: 20;
font-size: 12px;
padding: 6px 8px 8px;
top: 18px;
left: -11px;
width: 160px;
display: none;
cursor: pointer;
}
.rickshaw_annotation_timeline .annotation .content:before {
content: "\25b2";
position: absolute;
top: -11px;
color: white;
text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8);
}
.rickshaw_annotation_timeline .annotation.active,
.rickshaw_annotation_timeline .annotation:hover {
background-color: rgba(0, 0, 0, 0.8);
cursor: none;
}
.rickshaw_annotation_timeline .annotation .content:hover {
z-index: 50;
}
.rickshaw_annotation_timeline .annotation.active .content {
display: block;
}
.rickshaw_annotation_timeline .annotation:hover .content {
display: block;
z-index: 50;
}
.rickshaw_graph .y_axis,
.rickshaw_graph .x_axis_d3 {
fill: none;
}
.rickshaw_graph .y_ticks .tick line,
.rickshaw_graph .x_ticks_d3 .tick {
stroke: rgba(0, 0, 0, 0.16);
stroke-width: 2px;
shape-rendering: crisp-edges;
pointer-events: none;
}
.rickshaw_graph .y_grid .tick,
.rickshaw_graph .x_grid_d3 .tick {
z-index: -1;
stroke: rgba(0, 0, 0, 0.20);
stroke-width: 1px;
stroke-dasharray: 1 1;
}
.rickshaw_graph .y_grid .tick[data-y-value="0"] {
stroke-dasharray: 1 0;
}
.rickshaw_graph .y_grid path,
.rickshaw_graph .x_grid_d3 path {
fill: none;
stroke: none;
}
.rickshaw_graph .y_ticks path,
.rickshaw_graph .x_ticks_d3 path {
fill: none;
stroke: #808080;
}
.rickshaw_graph .y_ticks text,
.rickshaw_graph .x_ticks_d3 text {
opacity: 0.5;
font-size: 12px;
pointer-events: none;
}
.rickshaw_graph .x_tick.glow .title,
.rickshaw_graph .y_ticks.glow text {
fill: black;
color: black;
text-shadow: -1px 1px 0 rgba(255, 255, 255, 0.1),
1px -1px 0 rgba(255, 255, 255, 0.1),
1px 1px 0 rgba(255, 255, 255, 0.1),
0 1px 0 rgba(255, 255, 255, 0.1),
0 -1px 0 rgba(255, 255, 255, 0.1),
1px 0 0 rgba(255, 255, 255, 0.1),
-1px 0 0 rgba(255, 255, 255, 0.1),
-1px -1px 0 rgba(255, 255, 255, 0.1);
}
.rickshaw_graph .x_tick.inverse .title,
.rickshaw_graph .y_ticks.inverse text {
fill: white;
color: white;
text-shadow: -1px 1px 0 rgba(0, 0, 0, 0.8),
1px -1px 0 rgba(0, 0, 0, 0.8),
1px 1px 0 rgba(0, 0, 0, 0.8),
0 1px 0 rgba(0, 0, 0, 0.8),
0 -1px 0 rgba(0, 0, 0, 0.8),
1px 0 0 rgba(0, 0, 0, 0.8),
-1px 0 0 rgba(0, 0, 0, 0.8),
-1px -1px 0 rgba(0, 0, 0, 0.8);
}
.custom_rickshaw_graph {
position: relative;
left: 40px;
}
.custom_y_axis {
position: absolute;
width: 40px;
}
.custom_slider {
left: 40px;
}
.custom_x_axis {
position: relative;
left: 40px;
height: 30px;
}
/*detail*/
.rickshaw_graph .detail {
pointer-events: none;
position: absolute;
top: 0;
z-index: 2;
background: rgba(0, 0, 0, 0.1);
bottom: 0;
width: 1px;
transition: opacity 0.25s linear;
-moz-transition: opacity 0.25s linear;
-o-transition: opacity 0.25s linear;
-webkit-transition: opacity 0.25s linear;
}
.rickshaw_graph .detail.inactive {
opacity: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
}
.rickshaw_graph .detail .x_label {
font-family: Arial, sans-serif;
border-radius: 3px;
padding: 6px;
opacity: 0.5;
border: 1px solid #e0e0e0;
font-size: 12px;
position: absolute;
background: white;
white-space: nowrap;
}
.rickshaw_graph .detail .x_label.left {
left: 0;
}
.rickshaw_graph .detail .x_label.right {
right: 0;
}
.rickshaw_graph .detail .item {
position: absolute;
z-index: 2;
border-radius: 3px;
padding: 0.25em;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0;
background: rgba(0, 0, 0, 0.4);
color: white;
border: 1px solid rgba(0, 0, 0, 0.4);
margin-left: 1em;
margin-right: 1em;
margin-top: -1em;
white-space: nowrap;
}
.rickshaw_graph .detail .item.left {
left: 0;
}
.rickshaw_graph .detail .item.right {
right: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
background: rgba(0, 0, 0, 0.8);
}
.rickshaw_graph .detail .item:after {
position: absolute;
display: block;
width: 0;
height: 0;
content: "";
border: 5px solid transparent;
}
.rickshaw_graph .detail .item.left:after {
top: 1em;
left: -5px;
margin-top: -5px;
border-right-color: rgba(0, 0, 0, 0.8);
border-left-width: 0;
}
.rickshaw_graph .detail .item.right:after {
top: 1em;
right: -5px;
margin-top: -5px;
border-left-color: rgba(0, 0, 0, 0.8);
border-right-width: 0;
}
.rickshaw_graph .detail .dot {
width: 4px;
height: 4px;
margin-left: -3px;
margin-top: -3.5px;
border-radius: 5px;
position: absolute;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);
box-sizing: content-box;
-moz-box-sizing: content-box;
background: white;
border-width: 2px;
border-style: solid;
display: none;
background-clip: padding-box;
}
.rickshaw_graph .detail .dot.active {
display: block;
}
/*legend*/
.rickshaw_legend {
font-family: Arial;
font-size: 12px;
color: white;
background: #404040;
display: inline-block;
padding: 12px 5px;
border-radius: 2px;
position: relative;
float: right;
}
.rickshaw_legend:hover {
z-index: 10;
}
.rickshaw_legend .swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.rickshaw_legend .line {
clear: both;
line-height: 140%;
padding-right: 15px;
}
.rickshaw_legend .line .swatch {
display: inline-block;
margin-right: 3px;
border-radius: 2px;
}
.rickshaw_legend .label {
margin: 0;
white-space: nowrap;
display: inline;
font-size: inherit;
background-color: transparent;
color: inherit;
font-weight: normal;
line-height: normal;
padding: 0;
text-shadow: none;
}
.rickshaw_legend .action:hover {
opacity: 0.6;
}
.rickshaw_legend .action {
margin-right: 0.2em;
opacity: 0.2;
cursor: pointer;
font-size: 14px;
}
.rickshaw_legend .line.disabled {
opacity: 0.4;
}
.rickshaw_legend ul {
list-style-type: none;
padding: 0;
margin: 2px;
cursor: pointer;
}
.rickshaw_legend li {
padding: 0 0 0 2px;
min-width: 80px;
white-space: nowrap;
}
.rickshaw_legend li:hover {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.rickshaw_legend li:active {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.legend {
display: inline-block;
position: relative;
left: 8px;
}
.legend_container {
float: right;
padding-right: 10px;
width: 0;
z-index: 1;
position: relative;
opacity: 0.7;
}
.spaced {
margin-top: 20px !important;
}

@ -1,588 +0,0 @@
/*
* 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.
*/
var fromDate, toDate, currentDay = new Date();
var startDate = new Date(currentDay.getTime() - (60 * 60 * 24 * 100));
var endDate = new Date(currentDay.getTime());
var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
var groupId, stats;
// create a custom bar renderer that shift bars
Rickshaw.Graph.Renderer.BinaryBar = Rickshaw.Class.create(Rickshaw.Graph.Renderer.Bar, {
name: 'binary_bar',
render: function (args) {
args = args || {};
var graph = this.graph;
var series = args.series || graph.series;
var vis = args.vis || graph.vis;
vis.selectAll('*').remove();
var barWidth = this.barWidth(series.active()[0]);
var barXOffset = 0;
var activeSeriesCount = series.filter(function (s) {
return !s.disabled;
}).length;
var seriesBarWidth = this.unstack ? barWidth / activeSeriesCount : barWidth;
var transform = function (d) {
// add a matrix transform for negative values
var matrix = [1, 0, 0, (d.y < 0 ? -1 : 1), 0, (d.y < 0 ? graph.y.magnitude(Math.abs(d.y)) * 2 : 0)];
return "matrix(" + matrix.join(',') + ")";
};
var index = 0;
series.forEach(function (series) {
if (series.disabled) {
return;
}
var nodes = vis.selectAll("path")
.data(series.stack.filter(function (d) {
return d.y !== null
}))
.enter().append("svg:rect")
.attr("x", function (d) {
return graph.x(d.x) + barXOffset
})
.attr("y", function (d) {
return ((graph.y(index + Math.abs(d.y))) * (d.y < 0 ? -1 : 1 ))
})
.attr("width", seriesBarWidth)
.attr("height", function (d) {
return graph.y.magnitude(Math.abs(d.y))
})
.attr("transform", transform);
index++;
Array.prototype.forEach.call(nodes[0], function (n) {
n.setAttribute('fill', series.color);
});
if (this.unstack) {
barXOffset += seriesBarWidth;
}
}, this);
}
});
function initDate() {
currentDay = new Date();
}
var configObject = {
startOfWeek: 'monday',
separator: ' to ',
format: 'YYYY-MM-DD HH:mm',
autoClose: false,
time: {
enabled: true
},
shortcuts: 'hide',
endDate: currentDay,
maxDays: 2,
getValue: function () {
return this.value;
},
setValue: function (s) {
this.value = s;
}
};
var DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate);
$(document).ready(function () {
initDate();
groupId = getQueryParams().groupId;
$('#date-range').html(DateRange);
$('#date-range').dateRangePicker(configObject)
.bind('datepicker-apply', function (event, dateRange) {
$(this).addClass('active');
$(this).siblings().removeClass('active');
fromDate = dateRange.date1 != "Invalid Date" ? dateRange.date1.getTime() / 1000 : null;
toDate = dateRange.date2 != "Invalid Date" ? dateRange.date2.getTime() / 1000 : null;
getStats(fromDate, toDate);
}
);
getDateTime(currentDay.getTime() - 3600000, currentDay.getTime());
$('#hour-btn').addClass('active');
});
//hour
$('#hour-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - 3600000, currentDay.getTime());
});
//12 hours
$('#h12-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 12), currentDay.getTime());
});
//24 hours
$('#h24-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 24), currentDay.getTime());
});
//48 hours
$('#h48-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 48), currentDay.getTime());
});
$('body').on('click', '.btn-group button', function (e) {
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
function getDateTime(from, to) {
fromDate = from;
toDate = to;
startDate = new Date(from);
endDate = new Date(to);
DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate);
$('#date-range').html(DateRange);
getStats(from / 1000, to / 1000);
}
function getStats(from, to) {
var tzOffset = new Date().getTimezoneOffset() * 60 / 1000;
from += tzOffset;
to += tzOffset;
$('#div-chart').html('<div style="height:200px" data-state="loading" ' +
'data-loading-text="Loading..." data-loading-style="icon-only" ' +
'data-loading-inverse="true"></div>');
var requestData = {};
var getStatsRequest;
if (from) {
requestData['from'] = parseInt(from);
}
if (to) {
requestData['to'] = parseInt(to);
}
if (groupId && groupId != "0") {
requestData['groupId'] = groupId;
getStatsRequest = $.ajax({
url: "api/stats/group",
method: "GET",
data: requestData
});
} else {
var deviceId = getQueryParams().deviceId;
var deviceType = getQueryParams().deviceType;
requestData['deviceId'] = deviceId;
requestData['deviceType'] = deviceType;
getStatsRequest = $.ajax({
url: "api/stats",
method: "GET",
data: requestData
});
}
getStatsRequest.done(function (data) {
stats = data;
updateGraphs();
});
getStatsRequest.fail(function (jqXHR, textStatus) {
console.log("Request failed: " + jqXHR.statusText);
});
}
$(window).on('resize', function () {
if (stats) {
updateGraphs();
}
});
function updateGraphs() {
console.log(stats);
var graphId = 1;
$('#div-chart').html("");
for (var stats_data in stats) {
switch (stats[stats_data][0]["stream"]["ui_unit"]["name"]) {
case "cdmf.unit.analytics.line-chart":
$('#div-chart').append("<div class='row margin-double shrink'><div>" +
"<h2 class='grey'>" + stats[stats_data][0]["stream"]["name"] +
"</h2><hr><div id='canvas-wrapper" + graphId +
"'></div></div><hr class='spaced'></div>");
drawLineGraph(graphId++, stats[stats_data]);
break;
case "cdmf.unit.analytics.bar-chart":
$('#div-chart').append("<div class='row margin-double shrink'><div><h2 class='grey'>" +
stats[stats_data][0]["stream"]["name"] +
"</h2><hr><div id='canvas-wrapper" + graphId + "'></div></div>" +
"<hr class='spaced'></div>");
drawBarGraph(graphId++, stats[stats_data]);
break;
}
}
scaleGraphs();
}
function drawLineGraph(graphId, chartDataRaw) {
var chartWrapperElmId = "#canvas-wrapper" + graphId;
var graphWidth = $(chartWrapperElmId).width() - 50;
if (chartDataRaw.length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var chartDiv = "chart" + graphId;
var sliderDiv = "slider" + graphId;
var y_axis = "y_axis" + graphId;
$(chartWrapperElmId).html("").html('<div id = "' + y_axis + '" class="custom_y_axis"></div>' +
'<div class="legend_container" id="legend_container' +
graphId + '"><div id="smoother' + graphId +
'" title="Smoothing"></div><div class="legend" id="legend' +
graphId + '"></div></div><div id="' + chartDiv +
'" class="custom_rickshaw_graph"></div>' +
'<div class="custom_x_axis"></div><div id="' + sliderDiv +
'" class="custom_slider"></div>');
var graphConfig = {
element: document.getElementById(chartDiv),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: "linear",
unstack: true,
stack: false,
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
series: []
};
var tzOffset = new Date().getTimezoneOffset() * 60;
var min = Number.MAX_VALUE;
var max = Number.MIN_VALUE;
var range_min = 99999, range_max = 0;
for (var i = 0; i < chartDataRaw.length; i++) {
var chartData = [];
if (chartDataRaw[i].stats.length > 0) {
var max_val = parseInt(chartDataRaw[i].stats[0].value);
var min_val = max_val;
for (var j = 0; j < chartDataRaw[i].stats.length; j++) {
var y_val = parseInt(chartDataRaw[i].stats[j].value);
if (y_val > max_val) {
max_val = y_val;
} else if (y_val < min_val) {
min_val = y_val;
}
chartData.push({
x: parseInt(chartDataRaw[i].stats[j].time) - tzOffset,
y: y_val
});
}
if (range_max < max_val) {
range_max = max_val;
}
if (range_min > min_val) {
range_min = min_val;
}
graphConfig['series'].push({
'color': palette.color(),
'data': summerizeLine(chartData),
'name': chartDataRaw[i].device,
'scale': d3.scale.linear().domain(
[Math.min(min, min_val) - 5,
Math.max(max, max_val) + 5]).nice()
});
}
}
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y.Scaled({
graph: graph,
orientation: 'left',
element: document.getElementById(y_axis),
width: 40,
height: 410,
'scale': d3.scale.linear().domain([Math.min(min, range_min), Math.max(max, range_max)]).nice()
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById(sliderDiv)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById('legend' + graphId)
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
var date = '<span class="date">' +
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
}
function drawBarGraph(graphId, chartDataRaw) {
var chartWrapperElmId = "#canvas-wrapper" + graphId;
var graphWidth = $(chartWrapperElmId).width() - 50;
if (chartDataRaw.length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var chartDiv = "chart" + graphId;
var sliderDiv = "slider" + graphId;
var y_axis = "y_axis" + graphId;
$(chartWrapperElmId).html("").html('<div id = "' + y_axis + '" class="custom_y_axis"></div>' +
'<div class="legend_container" id="legend_container' +
graphId + '"><div id="smoother' + graphId +
'" title="Smoothing"></div><div class="legend" id="legend' +
graphId + '"></div></div><div id="' + chartDiv +
'" class="custom_rickshaw_graph"></div>' +
'<div class="custom_x_axis"></div><div id="' + sliderDiv +
'" class="custom_slider"></div>');
var graphConfig = {
element: document.getElementById(chartDiv),
width: graphWidth,
height: 50 * chartDataRaw.length,
strokeWidth: 0.5,
renderer: 'binary_bar',
offset: 'zero',
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
series: []
};
var tzOffset = new Date().getTimezoneOffset() * 60;
for (var i = 0; i < chartDataRaw.length; i++) {
var chartData = [];
if (chartDataRaw[i].stats.length > 0) {
for (var j = 0; j < chartDataRaw[i].stats.length; j++) {
chartData.push({
x: parseInt(chartDataRaw[i].stats[j].time) - tzOffset,
y: parseInt(chartDataRaw[i].stats[j].value > 0 ? 1 : 0)
});
}
graphConfig['series'].push({
'color': palette.color(),
'data': summerizeBar(chartData),
'name': chartDataRaw[i].device
});
}
}
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.registerRenderer(new Rickshaw.Graph.Renderer.BinaryBar({graph: graph}));
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById(y_axis),
width: 40,
height: 55 * chartDataRaw.length,
tickFormat: function (y) {
return '';
}
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById(sliderDiv)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById('legend' + graphId)
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
}
function scaleGraphs() {
var sliders = $('.right_handle');
if (sliders.length == 0) {
return;
}
var graphWidth = 0;
for (var i = 1; i < 10; i++) {
if ($('#canvas-wrapper' + i).length) {
graphWidth = $('#canvas-wrapper' + i).width() - 50;
break;
}
}
if (graphWidth <= 0) {
return;
}
//Scale graphs
var sliderX = graphWidth * 60 * 60000 / (toDate - fromDate);
if (sliderX < graphWidth) {
// fake handle move
if (sliderX < 50) {
sliderX = 50;
}
var edown = document.createEvent("HTMLEvents");
edown.initEvent("mousedown", true, true);
edown.clientX = graphWidth;
var emove = document.createEvent("HTMLEvents");
emove.initEvent("mousemove", true, true);
emove.clientX = sliderX;
var eup = document.createEvent("HTMLEvents");
eup.initEvent("mouseup", true, true);
for (var slider in sliders) {
sliders[slider].dispatchEvent(edown);
document.dispatchEvent(emove);
document.dispatchEvent(eup);
}
}
}
function convertDate(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
return date.getFullYear() + '-' + (('' + month).length < 2 ? '0' : '') + month + '-' +
(('' + day).length < 2 ? '0' : '') + day + " " + (('' + hour).length < 2 ? '0' : '') +
hour + ":" + (('' + minute).length < 2 ? '0' : '') + minute;
}
function summerizeLine(data) {
if (data.length > 1500) {
var nData = [];
var i = 1;
while (i < data.length) {
var t_avg = (data[i - 1].x + data[i].x) / 2;
var v_avg = (data[i - 1].y + data[i].y) / 2;
nData.push({x: t_avg, y: v_avg});
i += 2;
}
return summerizeLine(nData);
} else {
return data;
}
}
function summerizeBar(data) {
if (data.length > 1500) {
var nData = [];
var i = 1;
while (i < data.length - 1) {
var t_avg = (data[i - 1].x + data[i].x) / 2;
var v_avg = (data[i - 1].y + data[i].y + data[i + 1].y) / 3;
nData.push({x: t_avg, y: Math.round(v_avg)});
i += 2;
}
return summerizeBar(nData);
} else {
return data;
}
}
function getQueryParams() {
var qs = document.location.search.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}

@ -16,26 +16,6 @@
* under the License.
*/
/* ========================================================================
* methods/mixins
* ======================================================================== */
/* ========================================================================
* default values
* ======================================================================== */
@font-face {
font-family: "Roboto";
font-weight: 400;
font-style: "normal";
src: url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.eot");
src: url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.eot?#iefix") format("embedded-opentype"), local("Roboto Regular"), local("Roboto-Regular"), url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.woff2") format("woff2"), url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.woff") format("woff"), url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.ttf") format("truetype"), url("libs/theme-wso2_1.0/fonts/Roboto/Roboto-Regular.svg#Roboto") format("svg");
}
/* ========================================================================
* loading fonts
* ======================================================================== */
/* ========================================================================
* icon styles
* ======================================================================== */
.icon-success {
color: #5cb85c;
}

@ -1,4 +1,4 @@
{
"version": "1.0.0",
"extends" : "uuf.unit.theme"
"version": "1.0.0",
"extends": "uuf.unit.theme"
}

@ -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;

@ -521,9 +521,9 @@ FROM
(SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE_TYPE.NAME AS PLATFORM,
DM_ENROLMENT.OWNERSHIP AS OWNERSHIP,
DM_ENROLMENT.OWNERSHIP,
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
DM_DEVICE.TENANT_ID AS TENANT_ID
DM_DEVICE.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
@ -531,7 +531,30 @@ LEFT JOIN
DEVICE_ID,
POLICY_ID,
STATUS AS IS_COMPLIANT
FROM
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
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;
CREATE VIEW DEVICES_VIEW_2 AS
SELECT
DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE_DETAIL.DEVICE_MODEL,
DM_DEVICE_DETAIL.VENDOR,
DM_DEVICE_DETAIL.OS_VERSION,
DM_ENROLMENT.OWNERSHIP,
DM_ENROLMENT.OWNER,
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
DM_DEVICE_TYPE.NAME AS PLATFORM,
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
DM_DEVICE.TENANT_ID
FROM
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
WHERE
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
ORDER BY TENANT_ID, 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