charithag 9 years ago
commit fb52c5845d

@ -18,27 +18,44 @@
package org.wso2.carbon.apimgt.webapp.publisher; 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.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants; 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.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils; import org.wso2.carbon.utils.NetworkUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.ServletContext;
import java.util.*; import java.util.*;
public class APIPublisherUtil { 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 DEFAULT_API_VERSION = "1.0.0";
public static final String API_VERSION_PARAM="{version}"; public static final String API_VERSION_PARAM = "{version}";
public static final String API_PUBLISH_ENVIRONEMENT = "Production and Sandbox"; public static final String API_PUBLISH_ENVIRONEMENT = "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";
enum HTTPMethod { enum HTTPMethod {
GET, POST, DELETE, PUT, OPTIONS GET, POST, DELETE, PUT, OPTIONS
} }
@ -95,7 +112,9 @@ public class APIPublisherUtil {
} }
api.setResponseCache(APIConstants.DISABLED); api.setResponseCache(APIConstants.DISABLED);
String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() + "\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}"; String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig); api.setEndpointConfig(endpointConfig);
if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) { if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) {
@ -163,13 +182,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 * @param input inputString
* @return String modifiedString * @return String modifiedString
*/ */
private static String replaceEmailDomain(String input){ private static String replaceEmailDomain(String input) {
if(input!=null&& input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR) ){ if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR)) {
input=input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR,APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT); input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR, APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
} }
return input; return input;
} }
@ -184,13 +205,129 @@ public class APIPublisherUtil {
private static String checkAndSetVersionParam(String context) { private static String checkAndSetVersionParam(String context) {
// This is to support the new Pluggable version strategy // 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 the context does not contain any {version} segment, we use the default version strategy.
if(!context.contains(API_VERSION_PARAM)){ if (!context.contains(API_VERSION_PARAM)) {
if(!context.endsWith("/")){ if (!context.endsWith("/")) {
context = context + "/"; context = context + "/";
} }
context = context +API_VERSION_PARAM; context = context + API_VERSION_PARAM;
} }
return context; 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());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
} }

@ -25,205 +25,82 @@ import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.*; 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.*;
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.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil; import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil;
import org.wso2.carbon.base.MultitenantConstants;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class APIPublisherLifecycleListener implements LifecycleListener { public class APIPublisherLifecycleListener implements LifecycleListener {
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; 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"; @Override
private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context"; public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports"; ServletContext servletContext = context.getServletContext();
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured"; String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application"; boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; if (isManagedApi) {
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class); try {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
@Override Set<String> annotatedAPIClasses = annotationUtil.
public void lifecycleEvent(LifecycleEvent lifecycleEvent) { scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext,
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); annotatedAPIClasses);
ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); for (APIResourceConfiguration apiDefinition : apiDefinitions) {
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
if (isManagedApi) {
try { try {
AnnotationUtil annotationUtil = new AnnotationUtil(context); int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().
Set<String> annotatedAPIClasses = annotationUtil. getTenantId(apiConfig.getTenantDomain());
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext, annotatedAPIClasses); boolean isTenantActive = APIPublisherDataHolder.getInstance().
getTenantManager().isTenantActive(tenantId);
for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition); if (isTenantActive) {
try { apiConfig.init();
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain()); API api = APIPublisherUtil.getAPI(apiConfig);
boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId); APIPublisherService apiPublisherService =
if (isTenantActive) { APIPublisherDataHolder.getInstance().getApiPublisherService();
apiConfig.init(); if (apiPublisherService == null) {
API api = APIPublisherUtil.getAPI(apiConfig); throw new IllegalStateException(
APIPublisherService apiPublisherService = "API Publisher service is not initialized properly");
APIPublisherDataHolder.getInstance().getApiPublisherService(); }
if (apiPublisherService == null) { apiPublisherService.publishAPI(api);
throw new IllegalStateException( } else {
"API Publisher service is not initialized properly"); log.error("No tenant [" + apiConfig.getTenantDomain() + "] " +
} "found when publishing the Web app");
apiPublisherService.publishAPI(api); }
} else { } catch (Throwable e) {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp"); log.error("Error occurred while publishing API '" + apiConfig.getName() +
} "' with the context '" + apiConfig.getContext() +
} catch (Throwable e) { "' and version '" + apiConfig.getVersion() + "'", e);
log.error("Error occurred while publishing API '" + apiConfig.getName() + }
"' with the context '" + apiConfig.getContext() + }
"' and version '" + apiConfig.getVersion() + "'", e); } catch (IOException e) {
} log.error("Error encountered while discovering annotated classes", e);
} } catch (ClassNotFoundException e) {
} catch (IOException e) { log.error("Error while scanning class for annotations", e);
log.error("Error enconterd while discovering annotated classes", e); }
} catch (ClassNotFoundException e) { }
log.error("Error while scanning class for annotations", e); }
} }
}
} //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) {
return null;
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>();
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());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
} }

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

@ -18,6 +18,9 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.dao; 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.List;
import java.util.Map; import java.util.Map;
@ -26,15 +29,9 @@ public interface GadgetDataServiceDAO {
/** /**
* Method to get total filtered device count from a particular tenant. * 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. * @return Total filtered device count.
*/ */
int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException; int getTotalDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
int getActiveDeviceCount() throws GadgetDataServiceDAOException; int getActiveDeviceCount() throws GadgetDataServiceDAOException;
@ -50,9 +47,6 @@ public interface GadgetDataServiceDAO {
@SuppressWarnings("unused") @SuppressWarnings("unused")
int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException; int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException;
/** /**
* Method to get unmonitored device count. * Method to get unmonitored device count.
* *
@ -61,22 +55,36 @@ public interface GadgetDataServiceDAO {
@SuppressWarnings("unused") @SuppressWarnings("unused")
int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException; 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") @SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused") @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") @SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
throws GadgetDataServiceDAOException;
@SuppressWarnings("unused") @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") @SuppressWarnings("unused")
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException; List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused") @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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; 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 org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.Connection; import java.sql.Connection;
@ -37,122 +39,141 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class); private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class);
@Override @Override
public int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException { public int getTotalDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1; return this.getDeviceCount(null);
return this.getDeviceCount(filteringViewID, filters);
}
@Override
public int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCount(filteringViewID, filters);
} }
@Override @Override
public int getActiveDeviceCount() throws GadgetDataServiceDAOException { public int getActiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>(); Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "ACTIVE"); filters.put("CONNECTIVITY_STATUS", "ACTIVE");
return this.getDeviceCount(filteringViewID, filters); return this.getDeviceCount(filters);
} }
@Override @Override
public int getInactiveDeviceCount() throws GadgetDataServiceDAOException { public int getInactiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>(); Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "INACTIVE"); filters.put("CONNECTIVITY_STATUS", "INACTIVE");
return this.getDeviceCount(filteringViewID, filters); return this.getDeviceCount(filters);
} }
@Override @Override
public int getRemovedDeviceCount() throws GadgetDataServiceDAOException { public int getRemovedDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>(); Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "REMOVED"); filters.put("CONNECTIVITY_STATUS", "REMOVED");
return this.getDeviceCount(filteringViewID, filters); return this.getDeviceCount(filters);
} }
@Override @Override
public int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException { public int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>(); Map<String, Object> filters = new HashMap<>();
filters.put("IS_COMPLIANT", 0); filters.put("IS_COMPLIANT", 0);
return this.getDeviceCount(filteringViewID, filters); return this.getDeviceCount(filters);
} }
@Override @Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException { public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
Connection con; Connection con;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredNonCompliantDeviceCountsByFeatures = new HashMap<>(); List<Map<String, Object>> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
int totalRecordsCount = 0;
try { try {
con = this.getConnection(); con = this.getConnection();
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " + 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 = con.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
// executing query // executing query
rs = stmt.executeQuery(); rs = stmt.executeQuery();
// fetching query results // fetching query results
while (rs.next()) { while (rs.next()) {
filteredNonCompliantDeviceCountsByFeatures. totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
put(rs.getString("FEATURE_CODE"), rs.getInt("DEVICE_COUNT"));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
return filteredNonCompliantDeviceCountsByFeatures; PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
paginationResult.setRecordsTotal(totalRecordsCount);
return paginationResult;
} }
@Override @Override
public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException { public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>(); Map<String, Object> filters = new HashMap<>();
filters.put("POLICY_ID", -1); filters.put("POLICY_ID", -1);
return this.getDeviceCount(filteringViewID, filters); return this.getDeviceCount(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);
} }
@Override public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException { Connection con;
int filteringViewID = 1; PreparedStatement stmt = null;
return this.getDevicesWithDetails(filteringViewID, filters); ResultSet rs = null;
} int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
int filteredDeviceCount = 0;
@Override try {
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException { con = this.getConnection();
int filteringViewID = 2; String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
return this.getDevicesWithDetails(filteringViewID, filters); // 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; Connection con;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -160,13 +181,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
int filteredDeviceCount = 0; int filteredDeviceCount = 0;
try { try {
con = this.getConnection(); con = this.getConnection();
String sql; String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
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 = ?";
}
// appending filters to support advanced filtering options // appending filters to support advanced filtering options
// [1] appending filter columns // [1] appending filter columns
if (filters != null && filters.size() > 0) { if (filters != null && filters.size() > 0) {
@ -177,8 +192,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
stmt = con.prepareStatement(sql); stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist // [2] appending filter column values, if exist
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) { if (filters != null && filters.values().size() > 0) {
int i = 2; int i = 3;
for (Object value : filters.values()) { for (Object value : filters.values()) {
if (value instanceof Integer) { if (value instanceof Integer) {
stmt.setInt(i, (Integer) value); stmt.setInt(i, (Integer) value);
@ -202,7 +218,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCount; 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; Connection con;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -218,14 +234,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
} }
} }
if (filteringViewID == 1) { sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
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";
}
stmt = con.prepareStatement(sql); stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist // [2] appending filter column values, if exist
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
@ -254,12 +264,12 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCountsByPlatforms; 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; Connection con;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>(); Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
try { try {
con = this.getConnection(); con = this.getConnection();
String sql, advancedSqlFiltering = ""; String sql, advancedSqlFiltering = "";
@ -270,14 +280,55 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
} }
} }
if (filteringViewID == 1) { sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " + "AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
advancedSqlFiltering + "GROUP BY OWNERSHIP"; stmt = con.prepareStatement(sql);
} else { // [2] appending filter column values, if exist
// if filteringViewID == 2 stmt.setInt(1, tenantId);
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " + stmt.setString(2, nonCompliantFeatureCode);
advancedSqlFiltering + "GROUP BY OWNERSHIP"; 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); stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist // [2] appending filter column values, if exist
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
@ -306,7 +357,54 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDeviceCountsByOwnershipTypes; 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; Connection con;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -316,12 +414,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
try { try {
con = this.getConnection(); con = this.getConnection();
String sql; String sql;
if (filteringViewID == 1) { sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
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 = ?";
}
// appending filters to support advanced filtering options // appending filters to support advanced filtering options
// [1] appending filter columns, if exist // [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) { if (filters != null && filters.size() > 0) {
@ -361,6 +454,58 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
return filteredDevicesWithDetails; 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 { private Connection getConnection() throws SQLException {
return GadgetDataServiceDAOFactory.getConnection(); 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.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException; 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.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.sql.SQLException;
import java.util.Map; import java.util.Map;
@ -36,12 +38,12 @@ class GadgetDataServiceImpl implements GadgetDataService {
private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class); private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class);
@Override @Override
public int getTotalDeviceCount(Map<String, Object> filters) { public int getTotalDeviceCount() {
int totalDeviceCount; int totalDeviceCount;
try { try {
GadgetDataServiceDAOFactory.openConnection(); GadgetDataServiceDAOFactory.openConnection();
totalDeviceCount = GadgetDataServiceDAOFactory. totalDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getTotalDeviceCount(filters); getGadgetDataServiceDAO().getTotalDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) { } catch (GadgetDataServiceDAOException | SQLException e) {
totalDeviceCount = -1; totalDeviceCount = -1;
return totalDeviceCount; return totalDeviceCount;
@ -132,18 +134,34 @@ class GadgetDataServiceImpl implements GadgetDataService {
} }
@Override @Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() { public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) {
Map<String, Integer> nonCompliantDeviceCountsByFeatures = null; PaginationResult paginationResult = null;
try { try {
GadgetDataServiceDAOFactory.openConnection(); GadgetDataServiceDAOFactory.openConnection();
nonCompliantDeviceCountsByFeatures = paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCountsByFeatures(); getNonCompliantDeviceCountsByFeatures(paginationRequest);
} catch (GadgetDataServiceDAOException | SQLException e) { } catch (GadgetDataServiceDAOException | SQLException e) {
return null; return null;
} finally { } finally {
GadgetDataServiceDAOFactory.closeConnection(); 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 @Override

@ -521,9 +521,9 @@ FROM
(SELECT (SELECT
DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.ID AS DEVICE_ID,
DM_DEVICE_TYPE.NAME AS PLATFORM, DM_DEVICE_TYPE.NAME AS PLATFORM,
DM_ENROLMENT.OWNERSHIP AS OWNERSHIP, DM_ENROLMENT.OWNERSHIP,
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, 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 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 WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
LEFT JOIN LEFT JOIN
@ -531,7 +531,30 @@ LEFT JOIN
DEVICE_ID, DEVICE_ID,
POLICY_ID, POLICY_ID,
STATUS AS IS_COMPLIANT STATUS AS IS_COMPLIANT
FROM FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
ORDER BY DEVICE_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;

Loading…
Cancel
Save