diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java new file mode 100644 index 0000000000..65ade5cc3a --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java @@ -0,0 +1,45 @@ +/* + * 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.apimgt.annotations.api; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This class is the representation of custom developed Permission annotation. + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Permission { + + /** + * Represents the scope name. + * @return Returns scope name. + */ + String scope(); + + /** + * Represents the associated permissions. + * @return Returns list of permissions. + */ + String[] permissions(); + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 3ce653c6c8..fcb27541db 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,16 +18,17 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; 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.FaultGatewaysException; -import org.wso2.carbon.apimgt.api.model.API; -import org.wso2.carbon.apimgt.api.model.APIIdentifier; -import org.wso2.carbon.apimgt.api.model.APIStatus; -import org.wso2.carbon.apimgt.api.model.URITemplate; +import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -38,10 +39,7 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.xml.stream.XMLStreamException; import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; /** * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all @@ -50,96 +48,123 @@ import java.util.Map; public class APIPublisherServiceImpl implements APIPublisherService { private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); - private static final String PUBLISH_ACTION = "Publish"; - - @Override - public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException { - String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner()); - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - // Below code snippet is added to load API Lifecycle in tenant mode. - RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService(); - CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId), - CommonUtil.getRootSystemRegistry(tenantId)); - APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); - MultitenantUtils.getTenantDomain(api.getApiOwner()); - if (provider != null) { - if (provider.isDuplicateContextTemplate(api.getContext())) { - throw new APIManagementException( - "Error occurred while adding the API. A duplicate API" + - " context already exists for " + api.getContext()); - } - if (!provider.isAPIAvailable(api.getId())) { - provider.addAPI(api); - provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION); - if (log.isDebugEnabled()) { - log.debug("Successfully published API '" + api.getId().getApiName() + - "' with context '" + api.getContext() + "' and version '" - + api.getId().getVersion() + "'"); - } - } else { - api.setStatus(APIStatus.PUBLISHED); - provider.updateAPI(api); - if (log.isDebugEnabled()) { - log.debug("An API already exists with the name '" + api.getId().getApiName() + - "', context '" + api.getContext() + "' and version '" - + api.getId().getVersion() + "'. Thus, the API config is updated"); - } - } - provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api)); - } else { - throw new APIManagementException("API provider configured for the given API configuration " + - "is null. Thus, the API is not published"); - } - } catch (FileNotFoundException e) { - throw new APIManagementException("Failed to retrieve life cycle file ", e); - } catch (RegistryException e) { - throw new APIManagementException("Failed to access the registry ", e); - } catch (XMLStreamException e) { - throw new APIManagementException("Failed parsing the lifecycle xml.", e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - - private String createSwaggerDefinition(API api) { - Map httpVerbsMap = new HashMap<>(); - - for (URITemplate uriTemplate : api.getUriTemplates()) { - JsonObject response = new JsonObject(); - response.addProperty("200", ""); - - JsonObject responses = new JsonObject(); - responses.add("responses", response); - JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate()); - if (httpVerbs == null) { - httpVerbs = new JsonObject(); - } - httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), responses); - httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs); - } - - Iterator it = httpVerbsMap.entrySet().iterator(); - JsonObject paths = new JsonObject(); - while (it.hasNext()) { - Map.Entry pair = (Map.Entry) it.next(); - paths.add(pair.getKey(), pair.getValue()); - it.remove(); - } - - JsonObject info = new JsonObject(); - info.addProperty("title", api.getId().getApiName()); - info.addProperty("version", api.getId().getVersion()); - - JsonObject swaggerDefinition = new JsonObject(); - swaggerDefinition.add("paths", paths); - swaggerDefinition.addProperty("swagger", "2.0"); - swaggerDefinition.add("info", info); - - return swaggerDefinition.toString(); - } + private static final String PUBLISH_ACTION = "Publish"; + + @Override + public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException { + String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner()); + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + // Below code snippet is added to load API Lifecycle in tenant mode. + RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService(); + CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId), + CommonUtil.getRootSystemRegistry(tenantId)); + APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner()); + MultitenantUtils.getTenantDomain(api.getApiOwner()); + if (provider != null) { + if (provider.isDuplicateContextTemplate(api.getContext())) { + throw new APIManagementException( + "Error occurred while adding the API. A duplicate API" + + " context already exists for " + api.getContext()); + } + if (!provider.isAPIAvailable(api.getId())) { + provider.addAPI(api); + provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION); + if (log.isDebugEnabled()) { + log.debug("Successfully published API '" + api.getId().getApiName() + + "' with context '" + api.getContext() + "' and version '" + + api.getId().getVersion() + "'"); + } + } else { + api.setStatus(provider.getAPI(api.getId()).getStatus()); + provider.updateAPI(api); + if (log.isDebugEnabled()) { + log.debug("An API already exists with the name '" + api.getId().getApiName() + + "', context '" + api.getContext() + "' and version '" + + api.getId().getVersion() + "'. Thus, the API config is updated"); + } + } + provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api)); + } else { + throw new APIManagementException("API provider configured for the given API configuration " + + "is null. Thus, the API is not published"); + } + } catch (FileNotFoundException e) { + throw new APIManagementException("Failed to retrieve life cycle file ", e); + } catch (RegistryException e) { + throw new APIManagementException("Failed to access the registry ", e); + } catch (XMLStreamException e) { + throw new APIManagementException("Failed parsing the lifecycle xml.", e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + private String createSwaggerDefinition(API api) { + Map httpVerbsMap = new HashMap<>(); + List scopes = new ArrayList<>(); + + for (URITemplate uriTemplate : api.getUriTemplates()) { + JsonObject response = new JsonObject(); + response.addProperty("200", ""); + + JsonObject responses = new JsonObject(); + responses.add("responses", response); + JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate()); + if (httpVerbs == null) { + httpVerbs = new JsonObject(); + } + JsonObject httpVerb = new JsonObject(); + httpVerb.add("responses", response); + + httpVerb.addProperty("x-auth-type", "Application%20%26%20Application%20User"); + httpVerb.addProperty("x-throttling-tier", "Unlimited"); + if (uriTemplate.getScope() != null) { + httpVerb.addProperty("x-scope", uriTemplate.getScope().getName()); + scopes.add(uriTemplate.getScope()); + } + httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), httpVerb); + httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs); + } + + Iterator it = httpVerbsMap.entrySet().iterator(); + JsonObject paths = new JsonObject(); + while (it.hasNext()) { + Map.Entry pair = (Map.Entry) it.next(); + paths.add(pair.getKey(), pair.getValue()); + it.remove(); + } + + JsonObject info = new JsonObject(); + info.addProperty("title", api.getId().getApiName()); + info.addProperty("version", api.getId().getVersion()); + + JsonObject swaggerDefinition = new JsonObject(); + swaggerDefinition.add("paths", paths); + swaggerDefinition.addProperty("swagger", "2.0"); + swaggerDefinition.add("info", info); + + // adding scopes to swagger definition + if (!api.getScopes().isEmpty()) { + Gson gson = new Gson(); + JsonElement element = gson.toJsonTree(api.getScopes(), new TypeToken>() { + }.getType()); + if (element != null) { + JsonArray apiScopes = element.getAsJsonArray(); + JsonObject apim = new JsonObject(); + apim.add("x-wso2-scopes", apiScopes); + JsonObject wso2Security = new JsonObject(); + wso2Security.add("apim", apim); + swaggerDefinition.add("x-wso2-security", wso2Security); + } + } + if (log.isDebugEnabled()) { + log.debug("API swagger definition: " + swaggerDefinition.toString()); + } + return swaggerDefinition.toString(); + } @Override public void removeAPI(APIIdentifier id) throws APIManagementException { @@ -169,4 +194,5 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.debug("End of publishing the batch of APIs"); } } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index 9ae9340513..2e7c8caac7 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -18,47 +18,45 @@ 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.user.api.TenantManager; -import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.NetworkUtils; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +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"; - public static final String API_VERSION_PARAM="{version}"; - public static final String API_PUBLISH_ENVIRONEMENT = "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_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_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants"; + private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain"; - enum HTTPMethod { - GET, POST, DELETE, PUT, OPTIONS - } - - private static List httpMethods; - - static { - httpMethods = new ArrayList(5); - httpMethods.add(HTTPMethod.GET); - httpMethods.add(HTTPMethod.POST); - httpMethods.add(HTTPMethod.DELETE); - httpMethods.add(HTTPMethod.PUT); - httpMethods.add(HTTPMethod.OPTIONS); - } 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); @@ -67,25 +65,28 @@ 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); api.setStatus(APIStatus.CREATED); api.setTransports(config.getTransports()); api.setContextTemplate(config.getContextTemplate()); - api.setUriTemplates(config.getUriTemplates()); - Set environements = new HashSet<>(); - environements.add(API_PUBLISH_ENVIRONEMENT); - api.setEnvironments(environements); - Set tiers = new HashSet(); + Set environments = new HashSet<>(); + environments.add(API_PUBLISH_ENVIRONMENT); + api.setEnvironments(environments); + Set 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); @@ -95,7 +96,9 @@ public class APIPublisherUtil { } 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); if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) { @@ -106,35 +109,37 @@ public class APIPublisherUtil { Set tags = new HashSet<>(Arrays.asList(config.getTags())); api.addTags(tags); } - return api; - } - private static Set getURITemplates(String endpoint, String authType) { - Set uriTemplates = new LinkedHashSet(); - if (APIConstants.AUTH_NO_AUTHENTICATION.equals(authType)) { - for (HTTPMethod method : httpMethods) { - URITemplate template = new URITemplate(); - template.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION); - template.setHTTPVerb(method.toString()); - template.setResourceURI(endpoint); - template.setUriTemplate("/*"); - uriTemplates.add(template); + // adding scopes to the api + Set uriTemplates = config.getUriTemplates(); + Map apiScopes = new HashMap<>(); + + if (uriTemplates != null) { + // this creates distinct scopes list + for (URITemplate template : uriTemplates) { + Scope scope = template.getScope(); + if (scope != null) { + if (apiScopes.get(scope.getKey()) == null) { + apiScopes.put(scope.getKey(), scope); + } + } } - } else { - for (HTTPMethod method : httpMethods) { - URITemplate template = new URITemplate(); - if (HTTPMethod.OPTIONS.equals(method)) { - template.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION); - } else { - template.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN); + Set scopes = new HashSet<>(apiScopes.values()); + api.setScopes(scopes); + + // this has to be done because of the use of pass by reference + // where same object reference of scope should be available for both + // api scope and uri template scope + for (Scope scope : scopes) { + for (URITemplate template : uriTemplates) { + if (scope.getKey().equals(template.getScope().getKey())) { + template.setScope(scope); + } } - template.setHTTPVerb(method.toString()); - template.setResourceURI(endpoint); - template.setUriTemplate("/*"); - uriTemplates.add(template); } + api.setUriTemplates(uriTemplates); } - return uriTemplates; + return api; } public static String getServerBaseUrl() { @@ -163,13 +168,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; } @@ -184,13 +191,131 @@ 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 + * @param apiDef + * @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 uriTemplates = new LinkedHashSet<>(); + 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; + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java index 2f28fbe6a5..577f4efecb 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResource.java @@ -18,70 +18,71 @@ package org.wso2.carbon.apimgt.webapp.publisher.config; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "Resource") -public class APIResource{ - - private String AuthType; - private String HttpVerb; - private String Uri; - private String UriTemplate; - private String consumes; - private String produces; - - public String getAuthType() { - return AuthType; - } - - @XmlElement(name = "AuthType", required = true) - public void setAuthType(String authType) { - AuthType = authType; - } - - public String getHttpVerb() { - return HttpVerb; - } - - @XmlElement(name = "HttpVerb", required = true) - public void setHttpVerb(String httpVerb) { - HttpVerb = httpVerb; - } - - public String getUri() { - return Uri; - } - - @XmlElement(name = "Uri", required = true) - public void setUri(String uri) { - Uri = uri; - } - - public String getUriTemplate() { - return UriTemplate; - } - - @XmlElement(name = "UriTemplate", required = true) - public void setUriTemplate(String uriTemplate) { - UriTemplate = uriTemplate; - } - - public String getConsumes() { - return consumes; - } - - @XmlElement(name = "Consumes", required = true) - public void setConsumes(String consumes) { - this.consumes = consumes; - } - - public String getProduces() { - return produces; - } - - @XmlElement(name = "Produces", required = true) - public void setProduces(String produces) { - this.produces = produces; - } +import org.wso2.carbon.apimgt.api.model.Scope; + +public class APIResource { + + private String AuthType; + private String HttpVerb; + private String Uri; + private String UriTemplate; + private String consumes; + private String produces; + private Scope scope; + + public String getAuthType() { + return AuthType; + } + + public void setAuthType(String authType) { + AuthType = authType; + } + + public String getHttpVerb() { + return HttpVerb; + } + + public void setHttpVerb(String httpVerb) { + HttpVerb = httpVerb; + } + + public String getUri() { + return Uri; + } + + public void setUri(String uri) { + Uri = uri; + } + + public String getUriTemplate() { + return UriTemplate; + } + + public void setUriTemplate(String uriTemplate) { + UriTemplate = uriTemplate; + } + + public String getConsumes() { + return consumes; + } + + public void setConsumes(String consumes) { + this.consumes = consumes; + } + + public String getProduces() { + return produces; + } + + public void setProduces(String produces) { + this.produces = produces; + } + + public Scope getScope() { + return scope; + } + + public void setScope(Scope scope) { + this.scope = scope; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java new file mode 100644 index 0000000000..7d16d198b9 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java @@ -0,0 +1,45 @@ +/* + * 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.apimgt.webapp.publisher.config; + +/** + * This class represents the information related to permissions. + */ +public class PermissionConfiguration { + + private String scopeName; + private String[] permissions; + + public String getScopeName() { + return scopeName; + } + + public void setScopeName(String scope) { + this.scopeName = scope; + } + + public String[] getPermissions() { + return permissions; + } + + public void setPermissions(String[] permissions) { + this.permissions = permissions; + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java new file mode 100644 index 0000000000..651c285723 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.apimgt.webapp.publisher.config; + +/** + * Custom exception class of Permission related operations. + */ +public class PermissionManagementException extends Exception { + + private static final long serialVersionUID = -3151279311929070298L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public PermissionManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public PermissionManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public PermissionManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public PermissionManagementException() { + super(); + } + + public PermissionManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index 0b4a3cff91..f3ecf34620 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -24,206 +24,85 @@ 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); - - @Override - public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); - - if (isManagedApi) { - try { - AnnotationUtil annotationUtil = new AnnotationUtil(context); - Set annotatedAPIClasses = annotationUtil. - scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); - List apiDefinitions = annotationUtil.extractAPIInfo(servletContext, annotatedAPIClasses); - - for (APIResourceConfiguration apiDefinition : apiDefinitions) { - APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition); - try { - int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain()); - boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId); - if (isTenantActive) { - apiConfig.init(); - API api = APIPublisherUtil.getAPI(apiConfig); - APIPublisherService apiPublisherService = - APIPublisherDataHolder.getInstance().getApiPublisherService(); - if (apiPublisherService == null) { - throw new IllegalStateException( - "API Publisher service is not initialized properly"); - } - apiPublisherService.publishAPI(api); - } else { - log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp"); - } - } catch (Throwable 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 enconterd while discovering annotated classes", e); - } catch (ClassNotFoundException e) { - log.error("Error while scanning class for annotations", e); - } - } - } - } - - private List mergeAPIDefinitions(List 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 uriTemplates = new LinkedHashSet(); - 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; - } + 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) { + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + + if (isManagedApi) { + try { + AnnotationUtil annotationUtil = new AnnotationUtil(context); + Set annotatedAPIClasses = annotationUtil. + scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); + + List apiDefinitions = annotationUtil.extractAPIInfo(servletContext, + annotatedAPIClasses); + + for (APIResourceConfiguration apiDefinition : apiDefinitions) { + + APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); + + try { + int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). + getTenantId(apiConfig.getTenantDomain()); + + boolean isTenantActive = APIPublisherDataHolder.getInstance(). + getTenantManager().isTenantActive(tenantId); + + if (isTenantActive) { + apiConfig.init(); + API api = APIPublisherUtil.getAPI(apiConfig); + APIPublisherService apiPublisherService = + APIPublisherDataHolder.getInstance().getApiPublisherService(); + if (apiPublisherService == null) { + throw new IllegalStateException( + "API Publisher service is not initialized properly"); + } + apiPublisherService.publishAPI(api); + } else { + log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + + "found when publishing the Web app"); + } + } catch (Throwable 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) { + 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 mergeAPIDefinitions(List inputList) { + return null; + } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java index a26c2042f1..4974a54c0e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java @@ -20,12 +20,19 @@ package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; import org.apache.catalina.core.StandardContext; import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scannotation.AnnotationDB; import org.scannotation.WarUrlFinder; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.api.model.Scope; 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.PermissionConfiguration; +import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException; + import javax.servlet.ServletContext; import javax.ws.rs.*; import java.io.IOException; @@ -36,7 +43,9 @@ import java.lang.reflect.Proxy; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; public class AnnotationUtil { @@ -45,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 pathClazz; + Class apiClazz; private ClassLoader classLoader; private ServletContext servletContext; @@ -68,6 +78,7 @@ public class AnnotationUtil { /** * Scan the context for classes with annotations + * * @return * @throws IOException */ @@ -89,6 +100,7 @@ public class AnnotationUtil { /** * Method identifies the URL templates and context by reading the annotations of a class + * * @param entityClasses * @return */ @@ -107,38 +119,22 @@ public class AnnotationUtil { APIResourceConfiguration apiResourceConfig = null; try { clazz = classLoader.loadClass(className); - Class apiClazz = (Class) - classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); - Annotation apiAnno = clazz.getAnnotation(apiClazz); + apiClazz = (Class) + classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API + .class.getName()); + + Annotation apiAnno = clazz.getAnnotation(apiClazz); List 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) classLoader.loadClass(Path.class.getName()); @@ -177,7 +173,45 @@ public class AnnotationUtil { return apiResourceConfigs; } - private List 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 getApiResources(String resourceRootContext, String apiRootContext, + Method[] annotatedMethods) throws Throwable { List resourceList; resourceList = new ArrayList(); for (Method method : annotatedMethods) { @@ -195,35 +229,34 @@ public class AnnotationUtil { resource.setAuthType(AUTH_TYPE); Annotation[] annotations = method.getDeclaredAnnotations(); - for(int i=0; i consumesClass = (Class) classLoader.loadClass(Consumes.class.getName()); + for (int i = 0; i < annotations.length; i++) { + processHTTPMethodAnnotation(resource, annotations[i]); + if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) { + Class consumesClass = (Class) 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 producesClass = (Class) classLoader.loadClass(Produces.class.getName()); + if (annotations[i].annotationType().getName().equals(Produces.class.getName())) { + Class producesClass = (Class) classLoader.loadClass( + Produces.class.getName()); Method[] producesClassMethods = producesClass.getMethods(); Annotation producesAnno = method.getAnnotation(producesClass); resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR)); } + if (annotations[i].annotationType().getName().equals(Permission.class.getName())) { + PermissionConfiguration permissionConf = this.getPermission(method); + if (permissionConf != null) { + Scope scope = new Scope(); + scope.setKey(permissionConf.getScopeName()); + scope.setDescription(permissionConf.getScopeName()); + scope.setName(permissionConf.getScopeName()); + String roles = StringUtils.join(permissionConf.getPermissions(), ","); + scope.setRoles(roles); + resource.setScope(scope); + } + } } resourceList.add(resource); } @@ -231,12 +264,40 @@ public class AnnotationUtil { return resourceList; } - private String makeContextURLReady(String context){ - if(context != null && !context.equalsIgnoreCase("")){ - if(context.startsWith("/")){ + /** + * Read Method annotations indicating HTTP Methods + * @param resource + * @param annotation + */ + private void processHTTPMethodAnnotation(APIResource resource, Annotation annotation) { + if (annotation.annotationType().getName().equals(GET.class.getName())) { + resource.setHttpVerb(HttpMethod.GET); + } + if (annotation.annotationType().getName().equals(POST.class.getName())) { + resource.setHttpVerb(HttpMethod.POST); + } + if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) { + resource.setHttpVerb(HttpMethod.OPTIONS); + } + if (annotation.annotationType().getName().equals(DELETE.class.getName())) { + resource.setHttpVerb(HttpMethod.DELETE); + } + if (annotation.annotationType().getName().equals(PUT.class.getName())) { + resource.setHttpVerb(HttpMethod.PUT); + } + } + + /** + * Append '/' to the context and make it URL ready + * @param context + * @return + */ + private String makeContextURLReady(String context) { + if (context != null && !context.equalsIgnoreCase("")) { + if (context.startsWith("/")) { return context; - }else{ - return "/"+context; + } else { + return "/" + context; } } return ""; @@ -244,6 +305,7 @@ public class AnnotationUtil { /** * When an annotation and method is passed, this method invokes that executes said method against the annotation + * * @param method * @param annotation * @param returnType @@ -252,11 +314,11 @@ public class AnnotationUtil { */ private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable { InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); - switch (returnType){ + switch (returnType) { case STRING: return (String) methodHandler.invoke(annotation, method, null); case STRING_ARR: - return ((String[])methodHandler.invoke(annotation, method, null))[0]; + return ((String[]) methodHandler.invoke(annotation, method, null))[0]; default: return null; } @@ -267,6 +329,36 @@ public class AnnotationUtil { */ private String[] invokeMethod(Method method, Annotation annotation) throws Throwable { InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); - return ((String[])methodHandler.invoke(annotation, method, null)); + return ((String[]) methodHandler.invoke(annotation, method, null)); + } + + private PermissionConfiguration getPermission(Method currentMethod) throws Throwable { + Class permissionClass = (Class) classLoader.loadClass(Permission.class.getName()); + Annotation permissionAnnotation = currentMethod.getAnnotation(permissionClass); + if (permissionClass != null) { + Method[] permissionClassMethods = permissionClass.getMethods(); + PermissionConfiguration permissionConf = new PermissionConfiguration(); + for (Method method : permissionClassMethods) { + switch (method.getName()) { + case "scope": + permissionConf.setScopeName(invokeMethod(method, permissionAnnotation, STRING)); + break; + case "permissions": + String permissions[] = invokeMethod(method, permissionAnnotation); + this.addPermission(permissions); + permissionConf.setPermissions(permissions); + break; + } + } + return permissionConf; + } + return null; + } + + private void addPermission(String[] permissions) throws PermissionManagementException { + for (String permission : permissions) { + PermissionUtils.addPermission(permission); + } } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java new file mode 100644 index 0000000000..32c5bad855 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; + +import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException; +import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.registry.core.Registry; + +import java.util.StringTokenizer; + +/** + * Utility class which holds necessary utility methods required for persisting permissions in + * registry. + */ +public class PermissionUtils { + + public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; + public static final String PERMISSION_PROPERTY_NAME = "name"; + + public static Registry getGovernanceRegistry() throws PermissionManagementException { + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return APIPublisherDataHolder.getInstance().getRegistryService() + .getGovernanceSystemRegistry( + tenantId); + } catch (RegistryException e) { + throw new PermissionManagementException( + "Error in retrieving governance registry instance: " + + e.getMessage(), e); + } + } + + public static void addPermission(String permission) throws PermissionManagementException { + String resourcePermission = getAbsolutePermissionPath(permission); + try { + StringTokenizer tokenizer = new StringTokenizer(resourcePermission, "/"); + String lastToken = "", currentToken, tempPath; + while (tokenizer.hasMoreTokens()) { + currentToken = tokenizer.nextToken(); + tempPath = lastToken + "/" + currentToken; + if (!checkResourceExists(tempPath)) { + createRegistryCollection(tempPath, currentToken); + } + lastToken = tempPath; + } + } catch (RegistryException e) { + throw new PermissionManagementException("Error occurred while persisting permission : " + + resourcePermission, e); + } + } + + public static void createRegistryCollection(String path, String resourceName) + throws PermissionManagementException, + RegistryException { + Resource resource = PermissionUtils.getGovernanceRegistry().newCollection(); + resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName); + PermissionUtils.getGovernanceRegistry().beginTransaction(); + PermissionUtils.getGovernanceRegistry().put(path, resource); + PermissionUtils.getGovernanceRegistry().commitTransaction(); + } + + public static boolean checkResourceExists(String path) + throws PermissionManagementException, + org.wso2.carbon.registry.core.exceptions.RegistryException { + return PermissionUtils.getGovernanceRegistry().resourceExists(path); + } + + private static String getAbsolutePermissionPath(String permissionPath) { + return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java index 88fc682605..7c5b2038e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java @@ -18,6 +18,10 @@ 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.List; import java.util.Map; /** @@ -26,30 +30,61 @@ import java.util.Map; public interface GadgetDataService { @SuppressWarnings("unused") - int getTotalDeviceCount(Map filters); + int getTotalDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getActiveDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getInactiveDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getRemovedDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getNonCompliantDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getUnmonitoredDeviceCount() throws GadgetDataServiceException; + + @SuppressWarnings("unused") + PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getDeviceCount(Map filters) throws GadgetDataServiceException; + + @SuppressWarnings("unused") + int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getActiveDeviceCount(); + Map getDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getInactiveDeviceCount(); + Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getRemovedDeviceCount(); + Map getDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getNonCompliantDeviceCount(); + Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getUnmonitoredDeviceCount(); + PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceException; @SuppressWarnings("unused") - Map getNonCompliantDeviceCountsByFeatures(); + PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceException; @SuppressWarnings("unused") - Map getDeviceCountsByPlatforms(Map filters); + List> getDevicesWithDetails(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - Map getDeviceCountsByOwnershipTypes(Map filters); + List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java new file mode 100644 index 0000000000..32ebef29f0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java @@ -0,0 +1,82 @@ +/* + * 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.device.mgt.analytics.dashboard; + +/** + * Custom exception class for GadgetDataService layer. + */ +public class GadgetDataServiceException extends Exception { + + private String errorMessage; + private static final long serialVersionUID = 2021891706072918864L; + + /** + * Constructs a new exception with the specific error message and nested exception. + * + * @param errorMessage specific error message. + * @param nestedException Nested exception. + */ + public GadgetDataServiceException(String errorMessage, Exception nestedException) { + super(errorMessage, nestedException); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message and cause. + * + * @param errorMessage Specific error message. + * @param cause Cause of this exception. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(String errorMessage, Throwable cause) { + super(errorMessage, cause); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message. + * + * @param errorMessage Specific error message. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(String errorMessage) { + super(errorMessage); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message and cause. + * + * @param cause Cause of this exception. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(Throwable cause) { + super(cause); + } + + @SuppressWarnings("unused") + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java index adfb4359f6..6cbdba08bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAO.java @@ -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,57 +29,72 @@ 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 filters) throws GadgetDataServiceDAOException; - - @SuppressWarnings("unused") - int getFeatureNonCompliantDeviceCount(Map filters) throws GadgetDataServiceDAOException; + int getTotalDeviceCount() throws GadgetDataServiceDAOException; + /** + * Method to get active device count from a particular tenant. + * + * @return active device count. + */ int getActiveDeviceCount() throws GadgetDataServiceDAOException; + /** + * Method to get inactive device count from a particular tenant. + * + * @return inactive device count. + */ int getInactiveDeviceCount() throws GadgetDataServiceDAOException; + /** + * Method to get removed device count from a particular tenant. + * + * @return removed device count. + */ int getRemovedDeviceCount() throws GadgetDataServiceDAOException; /** - * Method to get non-compliant device count. + * Method to get non-compliant device count from a particular tenant. * * @return Non-compliant device count. */ - @SuppressWarnings("unused") int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") - Map getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException; - /** - * Method to get unmonitored device count. + * Method to get unmonitored device count from a particular tenant. * * @return Unmonitored device count. */ - @SuppressWarnings("unused") int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") + PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; + + int getDeviceCount(Map filters) throws GadgetDataServiceDAOException; + + int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException; + Map getDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") - Map getFeatureNonCompliantDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceDAOException; + Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException; + + Map getDeviceCountsByOwnershipTypes(Map filters) + throws GadgetDataServiceDAOException; + + Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") - Map getDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceDAOException; + PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") - Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceDAOException; + PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") List> getDevicesWithDetails(Map filters) throws GadgetDataServiceDAOException; - @SuppressWarnings("unused") - List> getFeatureNonCompliantDevicesWithDetails(Map filters) throws GadgetDataServiceDAOException; + List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java index 3ebf841f13..adb1917c1e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java @@ -18,11 +18,11 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao; -@SuppressWarnings("unused") /** - * Custom exception class for data access related exceptions. + * Custom exception class for GadgetDataServiceDAO layer. */ public class GadgetDataServiceDAOException extends Exception { + private String errorMessage; private static final long serialVersionUID = 2021891706072918864L; @@ -43,6 +43,7 @@ public class GadgetDataServiceDAOException extends Exception { * @param errorMessage Specific error message. * @param cause Cause of this exception. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(String errorMessage, Throwable cause) { super(errorMessage, cause); setErrorMessage(errorMessage); @@ -53,6 +54,7 @@ public class GadgetDataServiceDAOException extends Exception { * * @param errorMessage Specific error message. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(String errorMessage) { super(errorMessage); setErrorMessage(errorMessage); @@ -63,10 +65,12 @@ public class GadgetDataServiceDAOException extends Exception { * * @param cause Cause of this exception. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(Throwable cause) { super(cause); } + @SuppressWarnings("unused") public String getErrorMessage() { return errorMessage; } @@ -74,4 +78,5 @@ public class GadgetDataServiceDAOException extends Exception { public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java index bb2d44ac63..75555690cc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java @@ -33,6 +33,7 @@ import java.util.List; @SuppressWarnings("unused") public class GadgetDataServiceDAOFactory { + private static final Log log = LogFactory.getLog(GadgetDataServiceDAOFactory.class); private static DataSource dataSource; private static String databaseEngine; @@ -47,7 +48,7 @@ public class GadgetDataServiceDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error("Error occurred while retrieving config.datasource connection.", e); } } @@ -56,7 +57,7 @@ public class GadgetDataServiceDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error("Error occurred while retrieving config.datasource connection.", e); } } @@ -64,8 +65,8 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn != null) { throw new IllegalTransactionStateException("A transaction is already active within the context of " + - "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + - "transaction is already active is a sign of improper transaction handling"); + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling."); } conn = dataSource.getConnection(); currentConnection.set(conn); @@ -75,8 +76,8 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn == null) { throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods"); + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods."); } return conn; } @@ -85,36 +86,35 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn == null) { throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods"); + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods."); } try { conn.close(); } catch (SQLException e) { - log.warn("Error occurred while close the connection"); + log.warn("Error occurred while close the connection."); } currentConnection.remove(); } /** - * Resolve data source from the data source definition + * Resolve data source from the data source definition. * - * @param config data source configuration - * @return data source resolved from the data source definition + * @param config data source configuration. + * @return data source resolved from the data source definition. */ private static DataSource resolveDataSource(DataSourceConfig config) { DataSource dataSource = null; if (config == null) { throw new RuntimeException( - "Device Management Repository data source configuration " + "is null and " + - "thus, is not initialized"); + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized."); } JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); if (jndiConfig != null) { if (log.isDebugEnabled()) { - log.debug("Initializing Device Management Repository data source using the JNDI " + - "Lookup Definition"); + log.debug("Initializing Device Management Repository data source using the JNDI Lookup Definition."); } List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java index 8a842c3bdd..e4c4286ba1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java @@ -18,9 +18,9 @@ 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; @@ -33,126 +33,146 @@ import java.util.List; import java.util.Map; class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { - @SuppressWarnings("unused") - private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class); @Override - public int getTotalDeviceCount(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 1; - return this.getDeviceCount(filteringViewID, filters); - } - - @Override - public int getFeatureNonCompliantDeviceCount(Map 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 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 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 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 filters = new HashMap<>(); filters.put("IS_COMPLIANT", 0); - return this.getDeviceCount(filteringViewID, filters); + return this.getDeviceCount(filters); } @Override - public Map getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException { + public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException { + Map filters = new HashMap<>(); + filters.put("POLICY_ID", -1); + return this.getDeviceCount(filters); + } + + @Override + public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map filteredNonCompliantDeviceCountsByFeatures = new HashMap<>(); + List> 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 filteredNonCompliantDeviceCountByFeature; while (rs.next()) { - filteredNonCompliantDeviceCountsByFeatures. - put(rs.getString("FEATURE_CODE"), rs.getInt("DEVICE_COUNT")); + 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()) { + totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting non compliant device counts by features.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } - return filteredNonCompliantDeviceCountsByFeatures; - } - - @Override - public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException { - int filteringViewID = 1; - Map filters = new HashMap<>(); - filters.put("POLICY_ID", -1); - return this.getDeviceCount(filteringViewID, filters); - } - - @Override - public Map getDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 1; - return this.getDeviceCountsByPlatforms(filteringViewID, filters); - } - - @Override - public Map getFeatureNonCompliantDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 2; - return this.getDeviceCountsByPlatforms(filteringViewID, filters); + PaginationResult paginationResult = new PaginationResult(); + paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); + paginationResult.setRecordsTotal(totalRecordsCount); + return paginationResult; } - @Override - public Map getDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 1; - return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters); - } - - @Override - public Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 2; - return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters); - } - - @Override - public List> getDevicesWithDetails(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 1; - return this.getDevicesWithDetails(filteringViewID, filters); - } - - @Override - public List> getFeatureNonCompliantDevicesWithDetails(Map filters) throws GadgetDataServiceDAOException { - int filteringViewID = 2; - return this.getDevicesWithDetails(filteringViewID, filters); + public int getDeviceCount(Map 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 @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered device count.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return filteredDeviceCount; } - private int getDeviceCount(int filteringViewID, Map filters) throws GadgetDataServiceDAOException { + public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map filters) throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; @@ -160,13 +180,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 +191,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); @@ -195,14 +210,16 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCount = rs.getInt("DEVICE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered device count, " + + "non compliant by a particular feature.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } return filteredDeviceCount; } - private Map getDeviceCountsByPlatforms(int filteringViewID, Map filters) throws GadgetDataServiceDAOException { + public Map getDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; @@ -218,14 +235,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); @@ -247,19 +258,20 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { 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); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of device counts by platforms.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } return filteredDeviceCountsByPlatforms; } - private Map getDeviceCountsByOwnershipTypes(int filteringViewID, Map filters) throws GadgetDataServiceDAOException { + public Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, Map filters) throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map filteredDeviceCountsByOwnershipTypes = new HashMap<>(); + Map filteredDeviceCountsByPlatforms = new HashMap<>(); try { con = this.getConnection(); String sql, advancedSqlFiltering = ""; @@ -270,14 +282,56 @@ 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 @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a set of feature non-compliant device counts by platforms.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return filteredDeviceCountsByPlatforms; + } + + public Map getDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceDAOException { + Connection con; + PreparedStatement stmt = null; + ResultSet rs = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + Map 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); @@ -299,29 +353,229 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { 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); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of device counts by ownership types.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return filteredDeviceCountsByOwnershipTypes; + } + + public Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException { + Connection con; + PreparedStatement stmt = null; + ResultSet rs = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + Map 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 @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of feature " + + "non-compliant device counts by ownership types.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } return filteredDeviceCountsByOwnershipTypes; } - private List> getDevicesWithDetails(int filteringViewID, Map filters) throws GadgetDataServiceDAOException { + public PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map filteredDeviceWithDetails = new HashMap<>(); List> filteredDevicesWithDetails = new ArrayList<>(); + int totalRecordsCount = 0; try { con = this.getConnection(); - String sql; - if (filteringViewID == 1) { - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?"; + 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 DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " + + "WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; + 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++; + } + stmt.setInt(i, paginationRequest.getStartIndex()); + stmt.setInt(++i, paginationRequest.getRowCount()); } else { - // if filteringViewID == 2 - sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?"; + stmt.setInt(2, paginationRequest.getStartIndex()); + stmt.setInt(3, paginationRequest.getRowCount()); + } + // executing query + rs = stmt.executeQuery(); + // fetching query results + Map filteredDeviceWithDetails; + while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); + 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); } + // fetching total records count + sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?"; + + stmt = con.prepareStatement(sql); + stmt.setInt(1, tenantId); + + // executing query + rs = stmt.executeQuery(); + // fetching query results + while (rs.next()) { + totalRecordsCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of devices " + + "with details when pagination is enabled.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + PaginationResult paginationResult = new PaginationResult(); + paginationResult.setData(filteredDevicesWithDetails); + paginationResult.setRecordsTotal(totalRecordsCount); + return paginationResult; + } + + public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException { + Connection con; + PreparedStatement stmt = null; + ResultSet rs = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + List> filteredDevicesWithDetails = new ArrayList<>(); + int totalRecordsCount = 0; + 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 DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + + "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; + 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++; + } + stmt.setInt(i, paginationRequest.getStartIndex()); + stmt.setInt(++i, paginationRequest.getRowCount()); + } else { + stmt.setInt(3, paginationRequest.getStartIndex()); + stmt.setInt(4, paginationRequest.getRowCount()); + } + // executing query + rs = stmt.executeQuery(); + // fetching query results + Map filteredDeviceWithDetails; + while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); + 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); + } + // fetching total records count + sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " + + "WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; + + stmt = con.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, nonCompliantFeatureCode); + + // executing query + rs = stmt.executeQuery(); + // fetching query results + while (rs.next()) { + totalRecordsCount = rs.getInt("DEVICE_COUNT"); + } + } catch (SQLException e) { + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of feature non-compliant devices " + + "with details when pagination is enabled.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + PaginationResult paginationResult = new PaginationResult(); + paginationResult.setData(filteredDevicesWithDetails); + paginationResult.setRecordsTotal(totalRecordsCount); + return paginationResult; + } + + public List> getDevicesWithDetails(Map filters) throws GadgetDataServiceDAOException { + Connection con; + PreparedStatement stmt = null; + ResultSet rs = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + List> filteredDevicesWithDetails = new ArrayList<>(); + try { + con = this.getConnection(); + String sql; + 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) { @@ -346,7 +600,64 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { // executing query rs = stmt.executeQuery(); // fetching query results + Map filteredDeviceWithDetails; + while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); + 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 @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of devices with details.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return filteredDevicesWithDetails; + } + + public List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceDAOException { + Connection con; + PreparedStatement stmt = null; + ResultSet rs = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + List> 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 + Map filteredDeviceWithDetails; while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM")); filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP")); @@ -354,7 +665,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDevicesWithDetails.add(filteredDeviceWithDetails); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting filtered set of feature non-compliant devices with details.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java index 193afc92da..a506665f6f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java @@ -39,6 +39,7 @@ import org.wso2.carbon.ndatasource.core.DataSourceService; * unbind="unsetDataSourceService" */ public class GadgetDataServiceComponent { + private static final Log log = LogFactory.getLog(GadgetDataServiceComponent.class); protected void activate(ComponentContext componentContext) { @@ -56,10 +57,10 @@ public class GadgetDataServiceComponent { componentContext.getBundleContext(). registerService(GadgetDataService.class.getName(), new GadgetDataServiceImpl(), null); if (log.isDebugEnabled()) { - log.debug("Device Management Dashboard Analytics Bundle has been started successfully"); + log.debug("Device Management Dashboard Analytics Bundle has been started successfully."); } } catch (Throwable e) { - log.error("Error occurred while initializing the bundle", e); + log.error("Error occurred while initializing the bundle.", e); } } @@ -70,11 +71,18 @@ public class GadgetDataServiceComponent { //do nothing } - public void setDataSourceService(DataSourceService dataSourceService){ - + public void setDataSourceService(DataSourceService dataSourceService) { + if (log.isDebugEnabled()) { + log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService..."); + } + //do nothing } - public void unsetDataSourceService(DataSourceService dataSourceService){ - + public void unsetDataSourceService(DataSourceService dataSourceService) { + if (log.isDebugEnabled()) { + log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService..."); + } + //do nothing } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java index 6c52968183..b948d63aaa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java @@ -18,13 +18,15 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.internal; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; +import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataServiceException; 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.List; import java.util.Map; /** @@ -32,19 +34,18 @@ import java.util.Map; */ class GadgetDataServiceImpl implements GadgetDataService { - @SuppressWarnings("unused") - private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class); - @Override - public int getTotalDeviceCount(Map filters) { + public int getTotalDeviceCount() throws GadgetDataServiceException { int totalDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - totalDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getTotalDeviceCount(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - totalDeviceCount = -1; - return totalDeviceCount; + totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for total device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -52,15 +53,17 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public int getActiveDeviceCount() { + public int getActiveDeviceCount() throws GadgetDataServiceException { int activeDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - activeDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getActiveDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - activeDeviceCount = -1; - return activeDeviceCount; + activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for active device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -68,15 +71,17 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public int getInactiveDeviceCount() { + public int getInactiveDeviceCount() throws GadgetDataServiceException { int inactiveDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - inactiveDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getInactiveDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - inactiveDeviceCount = -1; - return inactiveDeviceCount; + inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for inactive device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -84,15 +89,17 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public int getRemovedDeviceCount() { + public int getRemovedDeviceCount() throws GadgetDataServiceException { int removedDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - removedDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getRemovedDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - removedDeviceCount = -1; - return removedDeviceCount; + removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for removed device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -100,15 +107,17 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public int getNonCompliantDeviceCount() { + public int getNonCompliantDeviceCount() throws GadgetDataServiceException { int nonCompliantDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - nonCompliantDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getNonCompliantDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - nonCompliantDeviceCount = -1; - return nonCompliantDeviceCount; + nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for non-compliant device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -116,15 +125,17 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public int getUnmonitoredDeviceCount() { + public int getUnmonitoredDeviceCount() throws GadgetDataServiceException { int unmonitoredDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - unmonitoredDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getUnmonitoredDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - unmonitoredDeviceCount = -1; - return unmonitoredDeviceCount; + unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for unmonitored device count.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -132,29 +143,77 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public Map getNonCompliantDeviceCountsByFeatures() { - Map nonCompliantDeviceCountsByFeatures = null; + public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getNonCompliantDeviceCountsByFeatures(paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for non-compliant device counts by features.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public int getDeviceCount(Map filters) throws GadgetDataServiceException { + int deviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for getting a filtered device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return deviceCount; + } + + @Override + public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map filters) + throws GadgetDataServiceException { + int featureNonCompliantDeviceCount; try { GadgetDataServiceDAOFactory.openConnection(); - nonCompliantDeviceCountsByFeatures = - GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCountsByFeatures(); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; + featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory. + getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting a filtered device count, non compliant by a particular feature.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } - return nonCompliantDeviceCountsByFeatures; + return featureNonCompliantDeviceCount; } @Override - public Map getDeviceCountsByPlatforms(Map filters) { - Map deviceCountsByPlatforms = null; + public Map getDeviceCountsByPlatforms(Map filters) + throws GadgetDataServiceException { + Map deviceCountsByPlatforms; try { GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByPlatforms = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getDeviceCountsByPlatforms(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; + deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDeviceCountsByPlatforms(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by platforms.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } @@ -162,18 +221,143 @@ class GadgetDataServiceImpl implements GadgetDataService { } @Override - public Map getDeviceCountsByOwnershipTypes(Map filters) { - Map deviceCountsByOwnershipTypes = null; + public Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + Map featureNonCompliantDeviceCountsByPlatforms; try { GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getDeviceCountsByOwnershipTypes(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; + featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory. + getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by platforms, non compliant by a particular feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDeviceCountsByPlatforms; + } + + @Override + public Map getDeviceCountsByOwnershipTypes(Map filters) + throws GadgetDataServiceException { + Map deviceCountsByOwnershipTypes; + try { + GadgetDataServiceDAOFactory.openConnection(); + deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDeviceCountsByOwnershipTypes(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by ownership types.", e); } finally { GadgetDataServiceDAOFactory.closeConnection(); } return deviceCountsByOwnershipTypes; } + @Override + public Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + Map featureNonCompliantDeviceCountsByOwnershipTypes; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDeviceCountsByOwnershipTypes = + GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by ownership types, non compliant by a particular feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDeviceCountsByOwnershipTypes; + } + + @Override + public PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDevicesWithDetails(filters, paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details when pagination is enabled.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details, non compliant by feature when pagination is enabled.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public List> getDevicesWithDetails(Map filters) + throws GadgetDataServiceException { + List> devicesWithDetails; + try { + GadgetDataServiceDAOFactory.openConnection(); + devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return devicesWithDetails; + } + + @Override + public List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + List> featureNonCompliantDevicesWithDetails; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details, non compliant by feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDevicesWithDetails; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Authentication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java similarity index 84% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Authentication.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java index 42257b7944..2eec7f26bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Authentication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Authentication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,12 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java index e1714c2c29..8b221bf24d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Certificate.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Certificate.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -25,12 +25,12 @@ import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.beans.EnrollmentCertificate; -import org.wso2.carbon.mdm.exception.Message; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate; +import org.wso2.carbon.device.mgt.jaxrs.exception.Message; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java index ac305b2008..80ad97ee6c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Configuration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Configuration.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; @@ -24,9 +24,9 @@ import org.apache.commons.logging.LogFactory; 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.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.MDMAppConstants; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import javax.ws.rs.Consumes; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java similarity index 78% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java index 487c93ada5..f70ab278a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Device.java @@ -16,21 +16,24 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import javax.ws.rs.DELETE; import javax.ws.rs.GET; +import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @@ -231,4 +234,52 @@ public class Device { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } -} \ No newline at end of file + + /** + * Update device. + * + * @return update status. + */ + @PUT + @Path("type/{type}/id/{deviceId}") + public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId, + org.wso2.carbon.device.mgt.common.Device updatedDevice) { + try { + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(deviceType); + deviceIdentifier.setId(deviceId); + org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier); + device.setName(updatedDevice.getName()); + device.setDescription(updatedDevice.getDescription()); + Boolean response = deviceManagementService.modifyEnrollment(device); + return Response.status(Response.Status.OK).entity(response).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * disenroll device. + * + * @return disenrollment status. + */ + @DELETE + @Path("type/{type}/id/{deviceId}") + public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) { + try { + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(deviceType); + deviceIdentifier.setId(deviceId); + Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier); + return Response.status(Response.Status.OK).entity(response).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching the list of device types."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java index 81fe19e73c..5bfe8e0b0f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceInformation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceInformation.java @@ -17,7 +17,7 @@ */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -26,7 +26,7 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; import javax.ws.rs.Path; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java index 0f85351571..0319ae349f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceNotification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceNotification.java @@ -16,15 +16,15 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import javax.ws.rs.Consumes; import javax.ws.rs.GET; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java index fc9a7bd3a6..f3fdf8c065 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/DeviceSearch.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/DeviceSearch.java @@ -17,7 +17,7 @@ */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.GET; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java index 9cd8c305e3..667d6f683a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Feature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Feature.java @@ -16,13 +16,13 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; import javax.ws.rs.GET; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java similarity index 92% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java index 71d91f97f0..acd9e98714 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Group.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java @@ -16,20 +16,20 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationResult; 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.service.GroupManagementProviderService; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -141,6 +141,26 @@ public class Group { } } + @Path("/all") + @GET + @Produces("application/json") + public Response getAllGroups() { + try { + GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils + .getGroupManagementProviderService(); + PaginationResult paginationResult = groupManagementProviderService + .getGroups(0, groupManagementProviderService.getGroupCount()); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult.getData()).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + @Path("/user/{user}") @GET @Produces("application/json") @@ -364,16 +384,18 @@ public class Group { } @GET - @Path("/owner/{owner}/name/{groupName}/devices/all") + @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") - public Response getDevices(@PathParam("groupName") String groupName, - @PathParam("owner") String owner) { + public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("start") int startIdx, @QueryParam("length") int length) { try { - List devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices( - groupName, owner); - Device[] deviceArray = new Device[devices.size()]; - devices.toArray(deviceArray); - return Response.status(Response.Status.OK).entity(deviceArray).build(); + PaginationResult paginationResult = DeviceMgtAPIUtils + .getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } } catch (GroupManagementException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); @@ -394,15 +416,12 @@ public class Group { } } - @PUT - @Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}") + @POST + @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") public Response addDevice(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @FormParam("userName") String userName) { + @PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) { try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( deviceIdentifier, groupName, owner); if (isAdded) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java index fbf0badc9a..73e78ceb83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/License.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/License.java @@ -16,14 +16,14 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import javax.ws.rs.GET; import javax.ws.rs.POST; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java index 50b141aa30..8ff77412bb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Operation.java @@ -16,11 +16,16 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil; +import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -31,14 +36,9 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.context.DeviceOperationContext; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.MDMAndroidOperationUtil; -import org.wso2.carbon.mdm.api.util.MDMIOSOperationUtil; -import org.wso2.carbon.mdm.api.util.ResponsePayload; -import org.wso2.carbon.mdm.beans.ApplicationWrapper; -import org.wso2.carbon.mdm.beans.MobileApp; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import javax.ws.rs.Consumes; import javax.ws.rs.GET; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java index 4878b32f9e..a0d789b00f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Policy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Policy.java @@ -16,18 +16,18 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; -import org.wso2.carbon.mdm.beans.PolicyWrapper; -import org.wso2.carbon.mdm.beans.PriorityUpdatedPolicyWrapper; -import org.wso2.carbon.mdm.util.MDMUtil; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; @@ -62,7 +62,7 @@ public class Policy { policy.setPolicyName(policyWrapper.getPolicyName()); policy.setProfileId(policyWrapper.getProfileId()); policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile())); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); policy.setOwnershipType(policyWrapper.getOwnershipType()); policy.setRoles(policyWrapper.getRoles()); policy.setUsers(policyWrapper.getUsers()); @@ -82,7 +82,7 @@ public class Policy { policy.setPolicyName(policyWrapper.getPolicyName()); policy.setProfileId(policyWrapper.getProfileId()); policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile())); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); policy.setOwnershipType(policyWrapper.getOwnershipType()); policy.setRoles(policyWrapper.getRoles()); policy.setUsers(policyWrapper.getUsers()); @@ -181,7 +181,7 @@ public class Policy { policy.setId(policyId); policy.setProfileId(policyWrapper.getProfileId()); policy.setDescription(policyWrapper.getDescription()); - policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile())); + policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile())); policy.setOwnershipType(policyWrapper.getOwnershipType()); policy.setRoles(policyWrapper.getRoles()); policy.setUsers(policyWrapper.getUsers()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java index 77569a649c..c9e0748be0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Profile.java @@ -16,12 +16,12 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java index d0e434c34f..c46f13bdb0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/Role.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Role.java @@ -16,18 +16,18 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; -import org.wso2.carbon.mdm.beans.RoleWrapper; -import org.wso2.carbon.mdm.util.SetReferenceTransformer; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserRealm; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java index bbfed9dad8..a64fae9cf3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/User.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/User.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.api; +package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpStatus; @@ -24,18 +24,18 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.api.util.CredentialManagementResponseBuilder; -import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.mdm.api.util.ResponsePayload; -import org.wso2.carbon.mdm.beans.UserCredentialWrapper; -import org.wso2.carbon.mdm.beans.UserWrapper; -import org.wso2.carbon.mdm.util.Constants; -import org.wso2.carbon.mdm.util.SetReferenceTransformer; +import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload; +import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorHandler.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorHandler.java similarity index 85% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorHandler.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorHandler.java index da8825b177..886572c303 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorHandler.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,11 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api.common; + +package org.wso2.carbon.device.mgt.jaxrs.api.common; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorMessage.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorMessage.java similarity index 84% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorMessage.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorMessage.java index 7dbe395532..e457484254 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/ErrorMessage.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/ErrorMessage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,11 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api.common; + +package org.wso2.carbon.device.mgt.jaxrs.api.common; public class ErrorMessage { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/MDMAPIException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/MDMAPIException.java similarity index 88% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/MDMAPIException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/MDMAPIException.java index 4139e56f46..d858bb1e26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/common/MDMAPIException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/common/MDMAPIException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,12 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api.common; +package org.wso2.carbon.device.mgt.jaxrs.api.common; /** * Custom exception class for handling CDM API related exceptions. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/context/DeviceOperationContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/context/DeviceOperationContext.java similarity index 87% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/context/DeviceOperationContext.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/context/DeviceOperationContext.java index aef30c70f2..d35e9dacd1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/context/DeviceOperationContext.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/context/DeviceOperationContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,12 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api.context; +package org.wso2.carbon.device.mgt.jaxrs.api.context; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java index 94f766f551..d9097edb93 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/CredentialManagementResponseBuilder.java @@ -16,14 +16,14 @@ * under the License. */ -package org.wso2.carbon.mdm.api.util; +package org.wso2.carbon.device.mgt.jaxrs.api.util; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.beans.UserCredentialWrapper; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java index d7cb8f940f..be97e21bd5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/DeviceMgtAPIUtils.java @@ -16,13 +16,14 @@ * under the License. */ -package org.wso2.carbon.mdm.api.util; +package org.wso2.carbon.device.mgt.jaxrs.api.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; @@ -34,7 +35,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.mdm.api.common.MDMAPIException; import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAndroidOperationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java similarity index 79% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAndroidOperationUtil.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java index e50fc0bde6..9dcbec0a3c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAndroidOperationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAndroidOperationUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,17 +11,20 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.api.util; +package org.wso2.carbon.device.mgt.jaxrs.api.util; + +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp; +import org.wso2.carbon.device.mgt.jaxrs.beans.android.AppStoreApplication; +import org.wso2.carbon.device.mgt.jaxrs.beans.android.EnterpriseApplication; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.beans.MobileApp; -import org.wso2.carbon.mdm.beans.android.WebApplication; +import org.wso2.carbon.device.mgt.jaxrs.beans.android.WebApplication; /** * @@ -45,15 +48,15 @@ public class MDMAndroidOperationUtil { switch (application.getType()) { case ENTERPRISE: - org.wso2.carbon.mdm.beans.android.EnterpriseApplication enterpriseApplication = - new org.wso2.carbon.mdm.beans.android.EnterpriseApplication(); + EnterpriseApplication enterpriseApplication = + new EnterpriseApplication(); enterpriseApplication.setType(application.getType().toString()); enterpriseApplication.setUrl(application.getLocation()); operation.setPayLoad(enterpriseApplication.toJSON()); break; case PUBLIC: - org.wso2.carbon.mdm.beans.android.AppStoreApplication appStoreApplication = - new org.wso2.carbon.mdm.beans.android.AppStoreApplication(); + AppStoreApplication appStoreApplication = + new AppStoreApplication(); appStoreApplication.setType(application.getType().toString()); appStoreApplication.setAppIdentifier(application.getIdentifier()); operation.setPayLoad(appStoreApplication.toJSON()); @@ -86,15 +89,15 @@ public class MDMAndroidOperationUtil { switch (application.getType()) { case ENTERPRISE: - org.wso2.carbon.mdm.beans.android.EnterpriseApplication enterpriseApplication = - new org.wso2.carbon.mdm.beans.android.EnterpriseApplication(); + EnterpriseApplication enterpriseApplication = + new EnterpriseApplication(); enterpriseApplication.setType(application.getType().toString()); enterpriseApplication.setAppIdentifier(application.getAppIdentifier()); operation.setPayLoad(enterpriseApplication.toJSON()); break; case PUBLIC: - org.wso2.carbon.mdm.beans.android.AppStoreApplication appStoreApplication = - new org.wso2.carbon.mdm.beans.android.AppStoreApplication(); + AppStoreApplication appStoreApplication = + new AppStoreApplication(); appStoreApplication.setType(application.getType().toString()); appStoreApplication.setAppIdentifier(application.getAppIdentifier()); operation.setPayLoad(appStoreApplication.toJSON()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAppConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAppConstants.java similarity index 63% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAppConstants.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAppConstants.java index a4a7f60714..5c1d919ca5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMAppConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMAppConstants.java @@ -1,20 +1,22 @@ /* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * Licensed 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 * - * 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. + * 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.mdm.api.util; + +package org.wso2.carbon.device.mgt.jaxrs.api.util; /** * This class holds all the constants used for IOS and Android. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMIOSOperationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java similarity index 70% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMIOSOperationUtil.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java index 261555d335..7014174801 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/MDMIOSOperationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/MDMIOSOperationUtil.java @@ -1,26 +1,31 @@ /* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * Licensed 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 * - * 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. + * 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.mdm.api.util; +package org.wso2.carbon.device.mgt.jaxrs.api.util; + +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; +import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp; +import org.wso2.carbon.device.mgt.jaxrs.beans.ios.AppStoreApplication; +import org.wso2.carbon.device.mgt.jaxrs.beans.ios.EnterpriseApplication; +import org.wso2.carbon.device.mgt.jaxrs.beans.ios.RemoveApplication; +import org.wso2.carbon.device.mgt.jaxrs.beans.ios.WebClip; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import org.wso2.carbon.mdm.beans.MobileApp; -import org.wso2.carbon.mdm.beans.ios.WebClip; import java.util.Properties; @@ -43,8 +48,8 @@ public class MDMIOSOperationUtil { switch (application.getType()) { case ENTERPRISE: - org.wso2.carbon.mdm.beans.ios.EnterpriseApplication enterpriseApplication = - new org.wso2.carbon.mdm.beans.ios.EnterpriseApplication(); + EnterpriseApplication enterpriseApplication = + new EnterpriseApplication(); enterpriseApplication.setBundleId(application.getId()); enterpriseApplication.setIdentifier(application.getIdentifier()); enterpriseApplication.setManifestURL(application.getLocation()); @@ -59,8 +64,8 @@ public class MDMIOSOperationUtil { operation.setType(Operation.Type.COMMAND); break; case PUBLIC: - org.wso2.carbon.mdm.beans.ios.AppStoreApplication appStoreApplication = - new org.wso2.carbon.mdm.beans.ios.AppStoreApplication(); + AppStoreApplication appStoreApplication = + new AppStoreApplication(); appStoreApplication.setRemoveAppUponMDMProfileRemoval((Boolean) application.getProperties(). get(MDMAppConstants.IOSConstants.IS_REMOVE_APP)); appStoreApplication.setIdentifier(application.getIdentifier()); @@ -96,8 +101,8 @@ public class MDMIOSOperationUtil { operation.setCode(MDMAppConstants.IOSConstants.OPCODE_REMOVE_APPLICATION); operation.setType(Operation.Type.PROFILE); - org.wso2.carbon.mdm.beans.ios.RemoveApplication removeApplication = - new org.wso2.carbon.mdm.beans.ios.RemoveApplication(); + RemoveApplication removeApplication = + new RemoveApplication(); removeApplication.setBundleId(application.getIdentifier()); operation.setPayLoad(removeApplication.toJSON()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/ResponsePayload.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/ResponsePayload.java similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/ResponsePayload.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/ResponsePayload.java index 6294000663..8fd94c619b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/api/util/ResponsePayload.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/util/ResponsePayload.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.api.util; +package org.wso2.carbon.device.mgt.jaxrs.api.util; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ApplicationWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java similarity index 58% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ApplicationWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java index ad2db850d0..4631e4e944 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ApplicationWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ApplicationWrapper.java @@ -1,23 +1,22 @@ /* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * 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 * - * 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. + * 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.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.util.List; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/EnrollmentCertificate.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java similarity index 96% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/EnrollmentCertificate.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java index bde1cf1a7c..40d94da4ed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/EnrollmentCertificate.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/EnrollmentCertificate.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; public class EnrollmentCertificate { String serial; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileApp.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java similarity index 92% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileApp.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java index 2f1ef19b3f..220b1572c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileApp.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileApp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,14 +11,13 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.beans; -import java.util.HashMap; -import java.util.Map; +package org.wso2.carbon.device.mgt.jaxrs.beans; + import java.util.Properties; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileAppTypes.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileAppTypes.java similarity index 77% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileAppTypes.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileAppTypes.java index 151f57c5f9..3997da90d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/MobileAppTypes.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/MobileAppTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,11 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.beans; + +package org.wso2.carbon.device.mgt.jaxrs.beans; public enum MobileAppTypes { ENTERPRISE,WEBAPP,PUBLIC diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java similarity index 93% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PolicyWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java index 931f98a867..c05fa535a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,12 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; import org.wso2.carbon.device.mgt.common.Device; import java.util.List; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PriorityUpdatedPolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java similarity index 74% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PriorityUpdatedPolicyWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java index ed0b7c56e7..20f5248f85 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/PriorityUpdatedPolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PriorityUpdatedPolicyWrapper.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * "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.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; public class PriorityUpdatedPolicyWrapper { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java similarity index 74% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/Profile.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java index 19e41d8852..a54b53b2c2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java @@ -1,22 +1,22 @@ /* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.carbon.mdm.beans; + * 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.device.mgt.jaxrs.beans; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ProfileFeature.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java similarity index 63% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ProfileFeature.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java index 0d56de0900..d52f30281b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ProfileFeature.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ProfileFeature.java @@ -1,26 +1,25 @@ /* -* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.carbon.mdm.beans; + * 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.device.mgt.jaxrs.beans; import com.google.gson.Gson; import java.io.Serializable; -import java.util.LinkedHashMap; public class ProfileFeature implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/RoleWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java similarity index 81% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/RoleWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java index c87640a7c3..b8d633f3f6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/RoleWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java @@ -1,24 +1,25 @@ -package org.wso2.carbon.mdm.beans; - -import org.wso2.carbon.user.mgt.common.UIPermissionNode; - /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import org.wso2.carbon.user.mgt.common.UIPermissionNode; + public class RoleWrapper { private String roleName; private String[] permissions; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserCredentialWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java similarity index 78% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserCredentialWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java index 91e2fd0ff7..d0c201b8d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserCredentialWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserCredentialWrapper.java @@ -1,22 +1,22 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * "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.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; public class UserCredentialWrapper { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java similarity index 97% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java index acdb9efcaf..c03a762ee3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/UserWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/UserWrapper.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.beans; +package org.wso2.carbon.device.mgt.jaxrs.beans; public class UserWrapper { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java new file mode 100644 index 0000000000..bc261e91a5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/AppStoreApplication.java @@ -0,0 +1,54 @@ +/* + * 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.device.mgt.jaxrs.beans.android; + +import com.google.gson.Gson; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + +import java.io.Serializable; + +/** + * This class represents the Appstore Application information. + */ +public class AppStoreApplication implements Serializable { + + private String type; + private String appIdentifier; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAppIdentifier() { + return appIdentifier; + } + + public void setAppIdentifier(String appIdentifier) { + this.appIdentifier = appIdentifier; + } + + public String toJSON() throws MDMAPIException { + Gson gson = new Gson(); + return gson.toJson(this); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java new file mode 100644 index 0000000000..22d0544602 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/EnterpriseApplication.java @@ -0,0 +1,63 @@ +/* + * 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.device.mgt.jaxrs.beans.android; + +import com.google.gson.Gson; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + +import java.io.Serializable; + +/** + * This class represents the Enterprise Application information. + */ +public class EnterpriseApplication implements Serializable { + + private String type; + private String url; + private String appIdentifier; + + public String getAppIdentifier() { + return appIdentifier; + } + + public void setAppIdentifier(String appIdentifier) { + this.appIdentifier = appIdentifier; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String toJSON() throws MDMAPIException { + Gson gson = new Gson(); + return gson.toJson(this); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java new file mode 100644 index 0000000000..74a0665c3d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/android/WebApplication.java @@ -0,0 +1,63 @@ +/* + * 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.device.mgt.jaxrs.beans.android; + +import com.google.gson.Gson; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + +import java.io.Serializable; + +/** + * This class represents the Web Application information. + */ +public class WebApplication implements Serializable { + + private String name; + private String url; + private String type; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String toJSON() throws MDMAPIException { + Gson gson = new Gson(); + return gson.toJson(this); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/AppStoreApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/AppStoreApplication.java similarity index 89% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/AppStoreApplication.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/AppStoreApplication.java index aa6c0a0121..dc00e924b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/AppStoreApplication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/AppStoreApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,15 +11,16 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.beans.ios; + +package org.wso2.carbon.device.mgt.jaxrs.beans.ios; import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + import java.io.Serializable; public class AppStoreApplication implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/EnterpriseApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/EnterpriseApplication.java similarity index 89% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/EnterpriseApplication.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/EnterpriseApplication.java index d310779faa..b33039f299 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/EnterpriseApplication.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/EnterpriseApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,16 +11,16 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * */ -package org.wso2.carbon.mdm.beans.ios; + +package org.wso2.carbon.device.mgt.jaxrs.beans.ios; import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + import java.io.Serializable; public class EnterpriseApplication implements Serializable { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/analytics.js b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/RemoveApplication.java similarity index 55% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/analytics.js rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/RemoveApplication.java index ea33e16405..08312523e7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/analytics.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/RemoveApplication.java @@ -16,20 +16,27 @@ * 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; +package org.wso2.carbon.device.mgt.jaxrs.beans.ios; + +import com.google.gson.Gson; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; + +import java.io.Serializable; + +public class RemoveApplication implements Serializable { + + private String bundleId; + + public String getBundleId() { + return bundleId; + } + + public void setBundleId(String bundleId) { + this.bundleId = bundleId; } - return {"title": title, "groupId": groupId}; + public String toJSON() throws MDMAPIException { + Gson gson = new Gson(); + return gson.toJson(this); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/WebClip.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/WebClip.java similarity index 56% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/WebClip.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/WebClip.java index 4604eab468..257c7663a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/WebClip.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ios/WebClip.java @@ -1,8 +1,25 @@ -package org.wso2.carbon.mdm.beans.ios; +/* + * 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.device.mgt.jaxrs.beans.ios; import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; +import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException; public class WebClip { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/Application.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/Application.java similarity index 74% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/Application.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/Application.java index 0a11ad1bc4..afbf6d87bd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/Application.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/Application.java @@ -1,23 +1,22 @@ /* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * 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 * - * 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. + * 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.mdm.common; +package org.wso2.carbon.device.mgt.jaxrs.common; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/GsonMessageBodyHandler.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/GsonMessageBodyHandler.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java index 09b49e6f1e..d2f9d2113f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/mdm/common/GsonMessageBodyHandler.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 @@ -11,12 +11,12 @@ * 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 + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -package org.wso2.mdm.common; +package org.wso2.carbon.device.mgt.jaxrs.common; import com.google.gson.Gson; import com.google.gson.GsonBuilder; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/BadRequestException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/BadRequestException.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java index adbe78069a..6ce60ffda3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/BadRequestException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.exception; +package org.wso2.carbon.device.mgt.jaxrs.exception; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/Message.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/Message.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/Message.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/Message.java index 4d5ee2ded3..e02151f3e0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/exception/Message.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/Message.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.exception; +package org.wso2.carbon.device.mgt.jaxrs.exception; public class Message { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java index 70651d64c9..533d6964ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.util; +package org.wso2.carbon.device.mgt.jaxrs.util; /** * Holds the constants used by Device Management Admin web application. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/MDMUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java similarity index 90% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/MDMUtil.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java index d766776cc3..c2f5c2b701 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/MDMUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java @@ -15,17 +15,18 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.mdm.util; -import org.wso2.carbon.mdm.beans.ProfileFeature; +package org.wso2.carbon.device.mgt.jaxrs.util; + +import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature; import org.wso2.carbon.policy.mgt.common.Profile; import java.util.ArrayList; import java.util.List; -public class MDMUtil { +public class DeviceMgtUtil { - public static Profile convertProfile(org.wso2.carbon.mdm.beans.Profile mdmProfile) { + public static Profile convertProfile(org.wso2.carbon.device.mgt.jaxrs.beans.Profile mdmProfile) { Profile profile = new Profile(); profile.setTenantId(mdmProfile.getTenantId()); profile.setCreatedDate(mdmProfile.getCreatedDate()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/SetReferenceTransformer.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/SetReferenceTransformer.java similarity index 97% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/SetReferenceTransformer.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/SetReferenceTransformer.java index da4136593e..f90e8c8a3f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/util/SetReferenceTransformer.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/SetReferenceTransformer.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.mdm.util; +package org.wso2.carbon.device.mgt.jaxrs.util; import java.util.ArrayList; import java.util.List; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/AppStoreApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/AppStoreApplication.java deleted file mode 100644 index b60ff7cdbd..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/AppStoreApplication.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed 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.mdm.beans.android; - -import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; -import java.io.Serializable; - -/** - * This class represents the Appstore Application information. - */ -public class AppStoreApplication implements Serializable { - - private String type; - private String appIdentifier; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getAppIdentifier() { - return appIdentifier; - } - - public void setAppIdentifier(String appIdentifier) { - this.appIdentifier = appIdentifier; - } - - public String toJSON() throws MDMAPIException { - Gson gson = new Gson(); - return gson.toJson(this); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/EnterpriseApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/EnterpriseApplication.java deleted file mode 100644 index f19dbd44c1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/EnterpriseApplication.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed 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.mdm.beans.android; - -import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; -import java.io.Serializable; - -/** - * This class represents the Enterprise Application information. - */ -public class EnterpriseApplication implements Serializable { - - private String type; - private String url; - private String appIdentifier; - - public String getAppIdentifier() { - return appIdentifier; - } - - public void setAppIdentifier(String appIdentifier) { - this.appIdentifier = appIdentifier; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String toJSON() throws MDMAPIException { - Gson gson = new Gson(); - return gson.toJson(this); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/WebApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/WebApplication.java deleted file mode 100644 index 7632524c9f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/android/WebApplication.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed 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.mdm.beans.android; - -import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; -import java.io.Serializable; - -/** - * This class represents the Web Application information. - */ -public class WebApplication implements Serializable { - - private String name; - private String url; - private String type; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String toJSON() throws MDMAPIException { - Gson gson = new Gson(); - return gson.toJson(this); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/RemoveApplication.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/RemoveApplication.java deleted file mode 100644 index 9c15ba6a36..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/mdm/beans/ios/RemoveApplication.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.wso2.carbon.mdm.beans.ios; - -import com.google.gson.Gson; -import org.wso2.carbon.mdm.api.common.MDMAPIException; -import java.io.IOException; -import java.io.Serializable; - -public class RemoveApplication implements Serializable { - - private String bundleId; - - public String getBundleId() { - return bundleId; - } - - public void setBundleId(String bundleId) { - this.bundleId = bundleId; - } - - public String toJSON() throws MDMAPIException { - Gson gson = new Gson(); - return gson.toJson(this); - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index e99164cdb2..e00d1a93ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -206,6 +206,20 @@ GET + + Modify user device + /device-mgt/user/devices/update + /devices/type/*/id/* + PUT + + + + Remove user device + /device-mgt/user/devices/remove + /devices/type/*/id/* + DELETE + + @@ -241,6 +255,13 @@ /devices/name/*/* GET + + + List All Own Devices + /device-mgt/user/devices/list + /devices/user/* + GET + @@ -938,12 +959,19 @@ - List All Groups + List All Groups with Pagination /device-mgt/admin/groups/list /groups GET + + List All Groups + /device-mgt/admin/groups/list + /groups/all + GET + + List Groups /device-mgt/user/groups/list @@ -1059,7 +1087,7 @@ List Group Devices /device-mgt/user/groups/devices/list - /groups/owner/*/name/*/devices/all + /groups/owner/*/name/*/devices GET @@ -1073,8 +1101,8 @@ Add Device to Group /device-mgt/user/groups/devices/add - /groups/owner/*/name/*/devices/*/* - PUT + /groups/owner/*/name/*/devices + POST diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index c6e489f7f8..05993e75ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -163,26 +163,24 @@ --> - - - - - - - - - - - - - - + + + + + + + + + + + + - - - - + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ProvisioningConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ProvisioningConfig.java new file mode 100644 index 0000000000..a82904001c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ProvisioningConfig.java @@ -0,0 +1,39 @@ +/* + * 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.device.mgt.common; + +public class ProvisioningConfig { + + private String providerTenantDomain; + private boolean isSharedWithAllTenants; + + public ProvisioningConfig(String providerTenantDomain, boolean sharedWithAllTenants) { + this.providerTenantDomain = providerTenantDomain; + isSharedWithAllTenants = sharedWithAllTenants; + } + + public String getProviderTenantDomain() { + return providerTenantDomain; + } + + public boolean isSharedWithAllTenants() { + return isSharedWithAllTenants; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java index dc6bcd886a..92af0d4544 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -51,6 +52,7 @@ public class DeviceInfo implements Serializable { private Double totalRAMMemory; private Double availableRAMMemory; private boolean pluggedIn; + private Date updatedTime; private Map deviceDetailsMap = new HashMap<>(); @@ -290,6 +292,17 @@ public class DeviceInfo implements Serializable { this.pluggedIn = pluggedIn; } + public Date getUpdatedTime() { + if(updatedTime.equals(null)){ + updatedTime = new Date(); + } + return updatedTime; + } + + public void setUpdatedTime(Date updatedTime) { + this.updatedTime = updatedTime; + } + public void setDeviceDetailsMap(Map deviceDetailsMap) { this.deviceDetailsMap = deviceDetailsMap; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java index 0b05406522..1368b92806 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java @@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; +import java.util.Date; public class DeviceLocation implements Serializable { @@ -39,6 +40,7 @@ public class DeviceLocation implements Serializable { private String state; private String zip; private String country; + private Date updatedTime; public int getDeviceId() { return deviceId; @@ -119,5 +121,16 @@ public class DeviceLocation implements Serializable { public void setCountry(String country) { this.country = country; } + + public Date getUpdatedTime() { + if(updatedTime.equals(null)){ + updatedTime = new Date(); + } + return updatedTime; + } + + public void setUpdatedTime(Date updatedTime) { + this.updatedTime = updatedTime; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java index a7263c3a69..cb404d1b92 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -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 users; private List 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()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java index 5f141c44d5..3496bacb8c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java @@ -31,7 +31,11 @@ public class Operation implements Serializable { } public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED + } + + public enum Control { + REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE } private String code; @@ -39,11 +43,13 @@ public class Operation implements Serializable { private Type type; private int id; private Status status; + private Control control; private String receivedTimeStamp; private String createdTimeStamp; private boolean isEnabled; private Object payLoad; private String operationResponse; + private String activityId; @Override public boolean equals(Object o) { @@ -87,6 +93,11 @@ public class Operation implements Serializable { if (status != operation.status) { return false; } + + if(control != operation.control){ + return false; + } + if (type != operation.type) { return false; } @@ -151,6 +162,14 @@ public class Operation implements Serializable { this.status = status; } + public Control getControl() { + return control; + } + + public void setControl(Control control) { + this.control = control; + } + public String getReceivedTimeStamp() { return receivedTimeStamp; } @@ -191,6 +210,14 @@ public class Operation implements Serializable { this.operationResponse = operationResponse; } + public String getActivityId() { + return activityId; + } + + public void setActivityId(String activityId) { + this.activityId = activityId; + } + @Override public String toString() { return "Operation{" + @@ -198,6 +225,7 @@ public class Operation implements Serializable { ", type=" + type + ", id=" + id + ", status=" + status + + ", control=" + control + ", receivedTimeStamp='" + receivedTimeStamp + '\'' + ", createdTimeStamp='" + createdTimeStamp + '\'' + ", isEnabled=" + isEnabled + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index 1d86b618f8..26ed93bddb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -85,4 +85,6 @@ public interface OperationManager { Operation getOperation(int operationId) throws OperationManagementException; + Operation getOperationByActivityId(String activity) throws OperationManagementException; + } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/PushNotificationConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/PushNotificationConfig.java new file mode 100644 index 0000000000..8bced1717e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/push/notification/PushNotificationConfig.java @@ -0,0 +1,41 @@ +/* + * 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.device.mgt.common.push.notification; + +import java.util.Set; + +public class PushNotificationConfig { + + private String type; + private Set properties; + + public PushNotificationConfig(String type, Set properties) { + this.type = type; + this.properties = properties; + } + + public String getType() { + return type; + } + + public Set getProperties() { + return properties; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java index 80bf030305..25f11458c1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java @@ -18,13 +18,11 @@ */ package org.wso2.carbon.device.mgt.common.spi; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; - -import java.util.List; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; /** * Composite interface that acts as the SPI exposing all device management as well as application management @@ -32,33 +30,16 @@ import java.util.List; */ public interface DeviceManagementService { - /** - * Method to retrieve the provider type that implements DeviceManager interface. - * - * @return Returns provider type - */ - String getType(); - - /** - * This returns the tenant domain of the provider. - * @return - */ - String getProviderTenantDomain(); - - /** - * returns true if the device type is shared between all tenants and false if its not. - * - * @return - */ - boolean isSharedWithAllTenants(); - void init() throws DeviceManagementException; + String getType(); + DeviceManager getDeviceManager(); ApplicationManager getApplicationManager(); - void notifyOperationToDevices(Operation operation, - List deviceIds) throws DeviceManagementException; + ProvisioningConfig getProvisioningConfig(); + + PushNotificationConfig getPushNotificationConfig(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index ad4a8e64ee..379ca8c3d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -75,4 +75,9 @@ public final class DeviceManagementConstants { public static final String DOWNLOAD_URL = "download-url"; } + public static final class OperationAttributes { + private OperationAttributes() {throw new AssertionError(); } + public static final String ACTIVITY = "ACTIVITY_"; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index 594d1be5e7..5403bf2a1b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -21,6 +21,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; @@ -44,8 +45,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { String deviceType = provider.getType(); - String tenantDomain = provider.getProviderTenantDomain(); - boolean isSharedWithAllTenants = provider.isSharedWithAllTenants(); + + ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); + String tenantDomain = provisioningConfig.getProviderTenantDomain(); + boolean isSharedWithAllTenants = provisioningConfig.isSharedWithAllTenants(); int tenantId = DeviceManagerUtil.getTenantId(tenantDomain); if (tenantId == -1) { throw new DeviceManagementException("No tenant available for tenant domain " + tenantDomain); @@ -57,7 +60,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis provider.init(); DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants); DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType, - provider.getDeviceManager().requireDeviceAuthorization()); + provider.getDeviceManager().requireDeviceAuthorization()); } } catch (DeviceManagementException e) { @@ -75,13 +78,15 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceTypeName=provider.getType(); - if(provider.isSharedWithAllTenants()){ - DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName); + String deviceTypeName = provider.getType(); + + ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); + if (provisioningConfig.isSharedWithAllTenants()) { + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName); providers.remove(deviceTypeIdentifier); - }else{ - int providerTenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain()); - DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName, providerTenantId); + } else { + int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId); providers.remove(deviceTypeIdentifier); } } @@ -113,15 +118,17 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis for (DeviceManagementService provider : providers.values()) { try { provider.init(); - int tenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain()); - DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provider.isSharedWithAllTenants()); + + ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); + int tenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); + DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provisioningConfig.isSharedWithAllTenants()); //TODO: //This is a temporory fix. //windows and IOS cannot resolve user info by extracting certs //until fix that, use following variable to enable and disable of checking user authorization. DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(provider.getType(), - provider.getDeviceManager().requireDeviceAuthorization()); + provider.getDeviceManager().requireDeviceAuthorization()); } catch (Throwable e) { /* Throwable is caught intentionally as failure of one plugin - due to invalid start up parameters, etc - should not block the initialization of other device management providers */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 2fca27bffc..a19f7c3f6a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -32,16 +32,13 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.app.mgt.oauth.ServiceAuthenticator; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException; import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub; import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO; @@ -56,9 +53,6 @@ import java.util.List; */ public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService { - private ConfigurationContext configCtx; - private ServiceAuthenticator authenticator; - private String oAuthAdminServiceUrl; private DeviceDAO deviceDAO; private ApplicationDAO applicationDAO; private ApplicationMappingDAO applicationMappingDAO; @@ -67,19 +61,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem private static final Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class); public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig) { - - IdentityConfigurations identityConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getIdentityConfigurations(); - this.authenticator = - new ServiceAuthenticator(identityConfig.getAdminUsername(), identityConfig.getAdminPassword()); - this.oAuthAdminServiceUrl = - identityConfig.getServerUrl() + DeviceManagementConstants.AppManagement.OAUTH_ADMIN_SERVICE; - try { - this.configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); - } catch (AxisFault e) { - throw new IllegalArgumentException("Error occurred while initializing Axis2 Configuration Context. " + - "Please check if an appropriate axis2.xml is provided", e); - } this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO(); this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO(); @@ -112,7 +93,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem @Override public void installApplicationForDevices(Operation operation, List deviceIds) throws ApplicationManagementException { - try { DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().addOperation(operation, deviceIds); DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().notifyOperationToDevices @@ -207,50 +187,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem } } - public void updateInstalledApplicationListOfDevice( - DeviceIdentifier deviceIdentifier, List applications) throws ApplicationManagementException { - } - - private OAuthConsumerAppDTO getAppInfo() throws ApplicationManagementException { - OAuthConsumerAppDTO appInfo = null; - try { - OAuthAdminServiceStub oAuthAdminServiceStub = - new OAuthAdminServiceStub(configCtx, oAuthAdminServiceUrl); - authenticator.authenticate(oAuthAdminServiceStub._getServiceClient()); - - try { - appInfo = oAuthAdminServiceStub.getOAuthApplicationDataByAppName( - DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME); - } - //application doesn't exist. Due to the way getOAuthApplicationDataByAppName has been - //implemented, it throws an AxisFault if the App doesn't exist. Hence the catch. - catch (AxisFault fault) { - oAuthAdminServiceStub.registerOAuthApplicationData(this.getRequestDTO()); - appInfo = oAuthAdminServiceStub.getOAuthApplicationDataByAppName( - DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME); - } - } catch (RemoteException e) { - handleException("Error occurred while retrieving app info", e); - } catch (OAuthAdminServiceException e) { - handleException("Error occurred while invoking OAuth admin service stub", e); - } - return appInfo; - } - - private OAuthConsumerAppDTO getRequestDTO() { - OAuthConsumerAppDTO appDTO = new OAuthConsumerAppDTO(); - appDTO.setApplicationName(DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME); - appDTO.setGrantTypes( - DeviceManagementConstants.AppManagement.OAUTH2_GRANT_TYPE_CLIENT_CREDENTIALS); - appDTO.setOAuthVersion(DeviceManagementConstants.AppManagement.OAUTH_VERSION_2); - return appDTO; - } - - private void handleException(String msg, Exception e) throws ApplicationManagementException { - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } - @Override public void updateApplicationListInstalledInDevice( DeviceIdentifier deviceIdentifier, List applications) throws ApplicationManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java index bdf7e9de8c..31dc99187a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java @@ -17,8 +17,14 @@ */ package org.wso2.carbon.device.mgt.core.config; +import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; +import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; +import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; + import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; /** * Represents Device Mgt configuration. @@ -27,6 +33,10 @@ import javax.xml.bind.annotation.XmlRootElement; public final class DeviceManagementConfig { private DeviceManagementConfigRepository deviceManagementConfigRepository; + private TaskConfiguration taskConfiguration; + private IdentityConfigurations identityConfigurations; + private PolicyConfiguration policyConfiguration; + //private List pushNotificationProviders; @XmlElement(name = "ManagementRepository", required = true) public DeviceManagementConfigRepository getDeviceManagementConfigRepository() { @@ -37,4 +47,43 @@ public final class DeviceManagementConfig { this.deviceManagementConfigRepository = deviceManagementConfigRepository; } + @XmlElement(name = "IdentityConfiguration", required = true) + public IdentityConfigurations getIdentityConfigurations() { + return identityConfigurations; + } + + + public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) { + this.identityConfigurations = identityConfigurations; + } + + @XmlElement(name = "PolicyConfiguration", required = true) + public PolicyConfiguration getPolicyConfiguration() { + return policyConfiguration; + } + + public void setPolicyConfiguration(PolicyConfiguration policyConfiguration) { + this.policyConfiguration = policyConfiguration; + } + + @XmlElement(name = "TaskConfiguration", required = true) + public TaskConfiguration getTaskConfiguration() { + return taskConfiguration; + } + + public void setTaskConfiguration(TaskConfiguration taskConfiguration) { + this.taskConfiguration = taskConfiguration; + } + +// @XmlElementWrapper(name = "PushNotificationProviders", required = true) +// @XmlElement(name = "Provider", required = true) +// public List getPushNotificationProviders() { +// return pushNotificationProviders; +// } +// +// public void setPushNotificationProviders(List pushNotificationProviders) { +// this.pushNotificationProviders = pushNotificationProviders; +// } + } + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java index 2ae0b77436..919865040a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java @@ -31,12 +31,7 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "ManagementRepository") public class DeviceManagementConfigRepository { - -// private EmailConfigurations emailConfigurations; - private TaskConfiguration taskConfiguration; private DataSourceConfig dataSourceConfig; - private IdentityConfigurations identityConfigurations; - private PolicyConfiguration policyConfiguration; @XmlElement(name = "DataSourceConfiguration", required = true) public DataSourceConfig getDataSourceConfig() { @@ -47,40 +42,4 @@ public class DeviceManagementConfigRepository { this.dataSourceConfig = dataSourceConfig; } -// @XmlElement(name = "EmailClientConfiguration", required = true) -// public EmailConfigurations getEmailConfigurations() { -// return emailConfigurations; -// } -// -// public void setEmailConfigurations(EmailConfigurations emailConfigurations) { -// this.emailConfigurations = emailConfigurations; -// } - - @XmlElement(name = "IdentityConfiguration", required = true) - public IdentityConfigurations getIdentityConfigurations() { - return identityConfigurations; - } - - - public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) { - this.identityConfigurations = identityConfigurations; - } - - @XmlElement(name = "PolicyConfiguration", required = true) - public PolicyConfiguration getPolicyConfiguration() { - return policyConfiguration; - } - - public void setPolicyConfiguration(PolicyConfiguration policyConfiguration) { - this.policyConfiguration = policyConfiguration; - } - - @XmlElement(name = "TaskConfiguration", required = true) - public TaskConfiguration getTaskConfiguration() { - return taskConfiguration; - } - - public void setTaskConfiguration(TaskConfiguration taskConfiguration) { - this.taskConfiguration = taskConfiguration; - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java index eacc7a84c8..f274eee845 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java @@ -45,23 +45,23 @@ import java.util.List; @SuppressWarnings("unused") public class WebAppDeploymentLifecycleListener implements LifecycleListener { - private static final String PERMISSION_CONFIG_PATH = "META-INF" + File.separator + "permissions.xml"; - private static final Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class); + private static final String PERMISSION_CONFIG_PATH = "META-INF" + File.separator + "permissions.xml"; + private static final Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class); - @Override - public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - String contextPath = context.getServletContext().getContextPath(); - try { - InputStream permissionStream = servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH); - if (permissionStream != null) { + @Override + public void lifecycleEvent(LifecycleEvent lifecycleEvent) { + if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { + StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); + ServletContext servletContext = context.getServletContext(); + String contextPath = context.getServletContext().getContextPath(); + try { + InputStream permissionStream = servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH); + if (permissionStream != null) { /* Un-marshaling Device Management configuration */ - JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class); - Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); - PermissionConfiguration permissionConfiguration = (PermissionConfiguration) - unmarshaller.unmarshal(permissionStream); + JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class); + Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); + PermissionConfiguration permissionConfiguration = (PermissionConfiguration) + unmarshaller.unmarshal(permissionStream); List permissions = permissionConfiguration.getPermissions(); String apiVersion = permissionConfiguration.getApiVersion(); if (permissionConfiguration != null && permissions != null) { @@ -69,22 +69,22 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener { // update the permission path to absolute permission path permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath())); permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion, - permission.getUrl()).toLowerCase()); + permission.getUrl()).toLowerCase()); permission.setMethod(permission.getMethod().toUpperCase()); PermissionManagerServiceImpl.getInstance().addPermission(permission); } - } - } - } catch (JAXBException e) { + } + } + } catch (JAXBException e) { log.error( "Exception occurred while parsing the permission configuration of webapp : " - + context.getServletContext().getContextPath(), e); + + context.getServletContext().getContextPath(), e); } catch (PermissionManagementException e) { log.error("Exception occurred while adding the permissions from webapp : " - + servletContext.getContextPath(), e); + + servletContext.getContextPath(), e); } } - } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java index deb10035bc..2f419755c4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/policy/PolicyConfiguration.java @@ -31,7 +31,7 @@ public class PolicyConfiguration { private int minRetriesToMarkUnreachable; private int minRetriesToMarkInactive; - @XmlElement(name = "monitoringClass", required = true) + @XmlElement(name = "MonitoringClass", required = true) public String getMonitoringClass() { return monitoringClass; } @@ -40,7 +40,7 @@ public class PolicyConfiguration { this.monitoringClass = monitoringClass; } - @XmlElement(name = "maxRetries", required = true) + @XmlElement(name = "MaxRetries", required = true) public int getMaxRetries() { return maxRetries; } @@ -49,7 +49,7 @@ public class PolicyConfiguration { this.maxRetries = maxRetries; } - @XmlElement(name = "minRetriesToMarkUnreachable", required = true) + @XmlElement(name = "MinRetriesToMarkUnreachable", required = true) public int getMinRetriesToMarkUnreachable() { return minRetriesToMarkUnreachable; } @@ -58,7 +58,7 @@ public class PolicyConfiguration { this.minRetriesToMarkUnreachable = minRetriesToMarkUnreachable; } - @XmlElement(name = "monitoringEnable", required = true) + @XmlElement(name = "MonitoringEnable", required = true) public boolean getMonitoringEnable() { return monitoringEnable; } @@ -67,7 +67,7 @@ public class PolicyConfiguration { this.monitoringEnable = monitoringEnable; } - @XmlElement(name = "minRetriesToMarkInactive", required = true) + @XmlElement(name = "MinRetriesToMarkInactive", required = true) public int getMinRetriesToMarkInactive() { return minRetriesToMarkInactive; } @@ -76,7 +76,7 @@ public class PolicyConfiguration { this.minRetriesToMarkInactive = minRetriesToMarkInactive; } - @XmlElement(name = "monitoringFrequency", required = true) + @XmlElement(name = "MonitoringFrequency", required = true) public int getMonitoringFrequency() { return monitoringFrequency; } @@ -84,4 +84,5 @@ public class PolicyConfiguration { public void setMonitoringFrequency(int monitoringFrequency) { this.monitoringFrequency = monitoringFrequency; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index 23c73b936b..3b392cc820 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -50,8 +50,8 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, DEVICE_MODEL, " + "VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, CONNECTION_TYPE, " + - "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN, UPDATE_TIMESTAMP) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceInfo.getDeviceId()); stmt.setString(2, deviceInfo.getDeviceModel()); @@ -68,6 +68,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt.setDouble(13, deviceInfo.getTotalRAMMemory()); stmt.setDouble(14, deviceInfo.getAvailableRAMMemory()); stmt.setBoolean(15, deviceInfo.isPluggedIn()); + stmt.setLong(16, System.currentTimeMillis()); stmt.execute(); @@ -83,7 +84,9 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { public void addDeviceProperties(Map 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; @@ -142,6 +145,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); } deviceInfo.setDeviceId(deviceId); @@ -224,7 +228,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " + - "STREET2, CITY, ZIP, STATE, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "STREET2, CITY, ZIP, STATE, COUNTRY, UPDATE_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceLocation.getDeviceId()); stmt.setDouble(2, deviceLocation.getLatitude()); stmt.setDouble(3, deviceLocation.getLongitude()); @@ -234,6 +238,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt.setString(7, deviceLocation.getZip()); stmt.setString(8, deviceLocation.getState()); stmt.setString(9, deviceLocation.getCountry()); + stmt.setLong(10, System.currentTimeMillis()); stmt.execute(); } catch (SQLException e) { throw new DeviceDetailsMgtDAOException("Error occurred while adding the device location to database.", e); @@ -266,6 +271,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { location.setZip(rs.getString("ZIP")); location.setState(rs.getString("STATE")); location.setCountry(rs.getString("COUNTRY")); + location.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); } location.setDeviceId(deviceId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java index 28c43cd6bd..bc132a9b20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java @@ -34,4 +34,8 @@ public class CommandOperation extends Operation { return Type.COMMAND; } + public Control getControl(){ + return Control.NO_REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java index bd4fc50ae6..c2be65a372 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java @@ -77,4 +77,9 @@ public class ConfigOperation extends Operation { return Type.CONFIG; } + + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java index 37e0736eb5..360deb868a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java @@ -18,8 +18,6 @@ */ package org.wso2.carbon.device.mgt.core.dto.operation.mgt; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.Properties; @@ -30,7 +28,11 @@ public class Operation implements Serializable { } public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED + } + + public enum Control { + REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE } private String code; @@ -38,6 +40,7 @@ public class Operation implements Serializable { private Type type; private int id; private Status status; + private Control control; private String receivedTimeStamp; private String createdTimeStamp; private boolean isEnabled; @@ -84,6 +87,14 @@ public class Operation implements Serializable { this.status = status; } + public Control getControl() { + return control; + } + + public void setControl(Control control) { + this.control = control; + } + public String getReceivedTimeStamp() { return receivedTimeStamp; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java index f1d97a0dd0..dc6ae4dd78 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java @@ -31,4 +31,8 @@ public class PolicyOperation extends Operation{ private List profileOperations; + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java index 61bb18d698..107cf091d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java @@ -26,4 +26,9 @@ public class ProfileOperation extends ConfigOperation implements Serializable { return Type.PROFILE; } + + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java index ce4183e9b3..c1e37bbd6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java @@ -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()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 10ca96f72a..7e8132fedf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -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 getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; + /** * Get the list of Device Groups in tenant. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 819d676dc7..1dc62b8046 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -178,6 +178,32 @@ public class GroupDAOImpl implements GroupDAO { } } + @Override + public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { + + PreparedStatement stmt = null; + ResultSet resultSet = null; + List 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 getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException { @@ -356,9 +382,9 @@ public class GroupDAOImpl implements GroupDAO { ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID as GROUP_ID " + + String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID " + "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " + - "WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?"; + "WHERE gm.GROUP_ID = dg.ID AND gm.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, groupName); stmt.setString(2, owner); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java index 4d175bfa74..28a0a2345d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java @@ -52,8 +52,9 @@ public class DeviceTaskManagerServiceComponent { log.debug("Initializing device details retrieving task manager bundle."); } // This will start the device details retrieving task. - boolean taskEnable = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getTaskConfiguration().isEnabled(); + boolean taskEnable = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration(). + isEnabled(); if (taskEnable) { DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl(); taskManagerService.startTask(); @@ -70,7 +71,6 @@ public class DeviceTaskManagerServiceComponent { @SuppressWarnings("unused") protected void deactivate(ComponentContext componentContext) { - try { DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl(); taskManagerService.stopTask(); @@ -93,6 +93,7 @@ public class DeviceTaskManagerServiceComponent { } DeviceManagementDataHolder.getInstance().setTaskService(null); } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java index 852142c1b8..3a9ecefca3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java @@ -35,5 +35,8 @@ public class CommandOperation extends Operation { public Type getType() { return Type.COMMAND; } + public Control getControl(){ + return Control.NO_REPEAT; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java index 83cfd0e612..69d8aafc4a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java @@ -78,4 +78,8 @@ public class ConfigOperation extends Operation { return Type.CONFIG; } + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 265dd02f8c..9e156618b6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -109,6 +109,12 @@ public class OperationManagerImpl implements OperationManager { OperationDAOUtil.convertOperation(operation); int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); for (EnrolmentInfo enrolmentInfo : enrolments) { + if(operationDto.getControl() == + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT){ + operationDAO.updateEnrollmentOperationsStatus(enrolmentInfo.getId(), operationDto.getCode(), + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.REPEATED); + } operationMappingDAO.addOperationMapping(operationId, enrolmentInfo.getId()); } OperationManagementDAOFactory.commitTransaction(); @@ -613,7 +619,7 @@ public class OperationManagerImpl implements OperationManager { public Operation getOperation(int operationId) throws OperationManagementException { Operation operation; try { - OperationManagementDAOFactory.getConnection(); + OperationManagementDAOFactory.openConnection(); org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. getOperation(operationId); if (dtoOperation == null) { @@ -648,6 +654,17 @@ public class OperationManagerImpl implements OperationManager { return operation; } + @Override + public Operation getOperationByActivityId(String activity) throws OperationManagementException { + // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. + int operationId = Integer.parseInt( + activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + if(operationId == 0){ + throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + } + return this.getOperation(operationId); + } + private OperationDAO lookupOperationDAO(Operation operation) { if (operation instanceof CommandOperation) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java index 0740728be0..6b36492a83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java @@ -33,4 +33,8 @@ public class PolicyOperation extends Operation { this.profileOperations = profileOperations; } + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java index 6c9abbed4c..f984fdfb0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java @@ -26,4 +26,8 @@ public class ProfileOperation extends ConfigOperation implements Serializable { return Type.PROFILE; } + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index c24887d1bf..9234953829 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -52,6 +52,9 @@ public interface OperationDAO { void updateOperationStatus(int enrolmentId, int operationId,Operation.Status status) throws OperationManagementDAOException; + void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, + Operation.Status newStatus) throws OperationManagementDAOException; + void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index b866285ff0..592be91c71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -105,6 +105,41 @@ public class GenericOperationDAOImpl implements OperationDAO { } } + @Override + public void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, + Operation.Status newStatus) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + try { + Connection connection = OperationManagementDAOFactory.getConnection(); + String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING AS EOM INNER JOIN DM_OPERATION DM " + + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? " + + "AND EOM.STATUS = ?;"; + stmt = connection.prepareStatement(query); + stmt.setInt(1, enrolmentId); + stmt.setString(2, operationCode); + stmt.setString(3, existingStatus.toString()); + // This will return only one result always. + rs = stmt.executeQuery(); + int id = 0; + while (rs.next()){ + id = rs.getInt("ID"); + } + if (id != 0){ + stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ? WHERE ID = ?"); + stmt.setString(1, newStatus.toString()); + stmt.setInt(2, id); + stmt.executeUpdate(); + } + + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + + "metadata", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt); + } + } + @Override public void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 44a93761a7..6625ceab89 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.util; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.*; public class OperationDAOUtil { @@ -94,6 +95,8 @@ public class OperationDAOUtil { operation.setReceivedTimeStamp(dtoOperation.getReceivedTimeStamp()); operation.setEnabled(dtoOperation.isEnabled()); operation.setProperties(dtoOperation.getProperties()); + operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + dtoOperation.getId()); + return operation; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java index 88affab477..4c7058be02 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java @@ -28,4 +28,6 @@ import java.util.List; public interface Processor { List execute(SearchContext searchContext) throws SearchMgtException; + + List getUpdatedDevices(long epochTime) throws SearchMgtException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java index db028edc19..c3e912fcb8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java @@ -38,4 +38,6 @@ public interface QueryBuilder { List processORProperties(List conditions) throws InvalidOperatorException; + String processUpdatedDevices(long epochTime) throws InvalidOperatorException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java index ad78ca171f..554ecfc0f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java @@ -27,5 +27,7 @@ import java.util.List; public interface SearchManagerService { List search(SearchContext searchContext) throws SearchMgtException; + + List getUpdated(long epochTime) throws SearchMgtException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java index e80da38167..ac8f670b7a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java @@ -34,7 +34,9 @@ import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; import java.sql.*; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class SearchDAOImpl implements SearchDAO { @@ -52,61 +54,62 @@ public class SearchDAOImpl implements SearchDAO { PreparedStatement stmt = null; ResultSet rs; List devices = new ArrayList<>(); + Map devs = new HashMap<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { - - Device device = new Device(); - device.setId(rs.getInt("ID")); - device.setDescription(rs.getString("DESCRIPTION")); - device.setName("NAME"); - device.setType(rs.getString("DEVICE_TYPE_NAME")); - device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setType(rs.getString("DEVICE_TYPE_NAME")); - identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceInfo deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceId(rs.getInt("ID")); - deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); - deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); - deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); - deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); - deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); - deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setIMEI(rs.getString("IMEI")); -// deviceInfo.setIMSI(rs.getString("IMSI")); - deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); -// deviceInfo.setOperator(rs.getString("OPERATOR")); - deviceInfo.setOsVersion(rs.getString("OS_VERSION")); - deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); - deviceInfo.setSsid(rs.getString("SSID")); - deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); - deviceInfo.setVendor(rs.getString("VENDOR")); - - DeviceLocation deviceLocation = new DeviceLocation(); - deviceLocation.setLatitude(rs.getDouble("LATITUDE")); - deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); - deviceLocation.setStreet1(rs.getString("STREET1")); - deviceLocation.setStreet2(rs.getString("STREET2")); - deviceLocation.setCity(rs.getString("CITY")); - deviceLocation.setState(rs.getString("STATE")); - deviceLocation.setZip(rs.getString("ZIP")); - deviceLocation.setCountry(rs.getString("COUNTRY")); - deviceLocation.setDeviceId(rs.getInt("ID")); - - DeviceWrapper wrapper = new DeviceWrapper(); - wrapper.setDevice(device); - wrapper.setDeviceInfo(deviceInfo); - wrapper.setDeviceLocation(deviceLocation); - wrapper.setDeviceIdentifier(identifier); - devices.add(wrapper); + if(!devs.containsKey(rs.getInt("ID"))) { + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName("NAME"); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + deviceLocation.setUpdatedTime(new java.util.Date(rs.getLong("DL_UPDATED_TIMESTAMP"))); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + devices.add(wrapper); + devs.put(device.getId(), device.getId()); + } } } catch (SQLException e) { @@ -134,61 +137,63 @@ public class SearchDAOImpl implements SearchDAO { PreparedStatement stmt = null; ResultSet rs; List devices = new ArrayList<>(); + Map devs = new HashMap<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { - - Device device = new Device(); - device.setId(rs.getInt("ID")); - device.setDescription(rs.getString("DESCRIPTION")); - device.setName(rs.getString("NAME")); - device.setType(rs.getString("DEVICE_TYPE_NAME")); - device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setType(rs.getString("DEVICE_TYPE_NAME")); - identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceInfo deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceId(rs.getInt("ID")); - deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); - deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); - deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); - deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); - deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); - deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setIMEI(rs.getString("IMEI")); -// deviceInfo.setIMSI(rs.getString("IMSI")); - deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); -// deviceInfo.setOperator(rs.getString("OPERATOR")); - deviceInfo.setOsVersion(rs.getString("OS_VERSION")); - deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); - deviceInfo.setSsid(rs.getString("SSID")); - deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); - deviceInfo.setVendor(rs.getString("VENDOR")); - - DeviceLocation deviceLocation = new DeviceLocation(); - deviceLocation.setLatitude(rs.getDouble("LATITUDE")); - deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); - deviceLocation.setStreet1(rs.getString("STREET1")); - deviceLocation.setStreet2(rs.getString("STREET2")); - deviceLocation.setCity(rs.getString("CITY")); - deviceLocation.setState(rs.getString("STATE")); - deviceLocation.setZip(rs.getString("ZIP")); - deviceLocation.setCountry(rs.getString("COUNTRY")); - deviceLocation.setDeviceId(rs.getInt("ID")); - - DeviceWrapper wrapper = new DeviceWrapper(); - wrapper.setDevice(device); - wrapper.setDeviceInfo(deviceInfo); - wrapper.setDeviceLocation(deviceLocation); - wrapper.setDeviceIdentifier(identifier); - devices.add(wrapper); + if(!devs.containsKey(rs.getInt("ID"))) { + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName(rs.getString("NAME")); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + deviceLocation.setUpdatedTime(new java.util.Date(rs.getLong("DL_UPDATED_TIMESTAMP"))); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + + devices.add(wrapper); + devs.put(device.getId(), device.getId()); + } } } catch (SQLException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index 4a97f1fdbe..55b377d4f5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -94,6 +94,28 @@ public class ProcessorImpl implements Processor { return aggregator.aggregate(deviceWrappers); } + @Override + public List getUpdatedDevices(long epochTime) throws SearchMgtException { + + if((1 + (int)Math.floor(Math.log10(epochTime))) <=10 ) { + epochTime = epochTime * 1000; + } + QueryBuilder queryBuilder = new QueryBuilderImpl(); + try { + String query = queryBuilder.processUpdatedDevices(epochTime); + DeviceManagementDAOFactory.openConnection(); + return searchDAO.searchDeviceDetailsTable(query); + } catch (InvalidOperatorException e) { + throw new SearchMgtException("Invalid operator was provided, so cannot execute the search.", e); + } catch (SQLException e) { + throw new SearchMgtException("Error occurred while managing database transactions.", e); + } catch (SearchDAOException e) { + throw new SearchMgtException("Error occurred while running the search operations for given time.", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + private List processANDSearch(List> deLists) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index cf4d2a03d6..5864966f0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -44,14 +44,14 @@ public class QueryBuilderImpl implements QueryBuilder { List orColumns = new ArrayList<>(); List otherANDColumns = new ArrayList<>(); List 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())) { + con.getOperator() + Utils.getConvertedValue(con.getKey(), con.getValue()); + } 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())) { + con.getOperator() + Utils.getConvertedValue(con.getKey(), con.getValue()); + } else if (Utils.checkDeviceLocationColumns(con.getKey())) { querySuffix = querySuffix + " OR DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); } @@ -158,6 +158,12 @@ public class QueryBuilderImpl implements QueryBuilder { return this.getQueryList(conditions); } + @Override + public String processUpdatedDevices(long epochTime) throws InvalidOperatorException { + return this.getGenericQueryPart() + " AND ( DD.UPDATE_TIMESTAMP > " + epochTime + + " OR DL.UPDATE_TIMESTAMP > " + epochTime + " )"; + } + private List getQueryList(List conditions) { List queryList = new ArrayList<>(); for (Condition con : conditions) { @@ -189,8 +195,9 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + - "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + - "DL.STATE, DL.COUNTRY FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP " + + "FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + "DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -205,8 +212,9 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + - "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + - "DL.STATE, DL.COUNTRY, DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP, " + + "DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + "DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, \n" + "DM_DEVICE_INFO AS DI, DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java index 888f3edc36..cc9a51d919 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java @@ -40,5 +40,10 @@ public class SearchManagerServiceImpl implements SearchManagerService { public List search(SearchContext searchContext) throws SearchMgtException { return processor.execute(searchContext); } + + @Override + public List getUpdated(long epochTime) throws SearchMgtException { + return processor.getUpdatedDevices(epochTime); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index cef647d727..3522228511 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -28,43 +28,100 @@ import java.util.Map; public class Utils { - public static Map getDeviceDetailsColumnNames() { + private static Map genericColumnsMap = new HashMap<>(); + private static Map 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"); + + } + + public static boolean checkColumnType(String column) { + + boolean bool = false; + + switch (column) { + case "deviceModel": + bool = true; + break; + case "vendor": + bool = true; + break; + case "osVersion": + bool = true; + break; + case "connectionType": + bool = true; + break; + case "ssid": + bool = true; + break; + default: bool =false; + break; + } - Map 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; + return bool; + } + + public static String getConvertedValue(String column, String value) { + + if(checkColumnType(column)){ + return "\'" + value + "\'"; + } else return value; + + } + + public static Map getDeviceDetailsColumnNames() { + return genericColumnsMap; } public static Map getDeviceLocationColumnNames() { - Map 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 convertStringToList(String str) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 73487be49c..9d5e6b46d5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -753,17 +753,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public void notifyOperationToDevices(Operation operation, List deviceIds) throws DeviceManagementException { - try { - for (DeviceIdentifier deviceId : deviceIds) { - DeviceManagementService dms = - getPluginRepository().getDeviceManagementService(deviceId.getType(), this.getTenantId()); - dms.notifyOperationToDevices(operation, deviceIds); - } - } catch (DeviceManagementException deviceMgtEx) { - String errorMsg = "Error in notify operations to plugins for app installation:" + - deviceMgtEx.getErrorMessage(); - log.error(errorMsg, deviceMgtEx); - throw new DeviceManagementException(errorMsg, deviceMgtEx); + for (DeviceIdentifier deviceId : deviceIds) { + DeviceManagementService dms = + getPluginRepository().getDeviceManagementService(deviceId.getType(), this.getTenantId()); + //TODO FIX THIS WITH PUSH NOTIFICATIONS + //dms.notifyOperationToDevices(operation, deviceIds); } } @@ -873,6 +867,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return DeviceManagementDataHolder.getInstance().getOperationManager().getOperation(operationId); } + @Override + public Operation getOperationByActivityId(String activity) throws OperationManagementException { + return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityId(activity); + } + @Override public List getDevicesOfUser(String username) throws DeviceManagementException { List devices = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 6c64b7cf03..b9ffa03340 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -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 getGroups(String username, String permission) throws GroupManagementException; + /** + * Get the group of device. + * @param deviceIdentifier + * @return + * @throws GroupManagementException + */ + List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index fabbaceb96..e20e033735 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -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 getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException { + DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); + List deviceGroups = new ArrayList<>(); + try { + Device device = managementProviderService.getDevice(deviceIdentifier); + GroupManagementDAOFactory.openConnection(); + List 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 groups, String role) throws GroupManagementException { try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java index 7f4537fa5c..f0997ce4b2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java @@ -22,18 +22,16 @@ package org.wso2.carbon.device.mgt.core.task; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.HashMap; +import java.util.Map; public class Utils { - - public static HashMap getTenantedTaskOperationMap(HashMap> map) { - + public static Map getTenantedTaskOperationMap(Map> map) { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (map.containsKey(tenantId)) { return map.get(tenantId); } else { - HashMap mp = new HashMap<>(); + Map mp = new HashMap<>(); map.put(tenantId, mp); return mp; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java index cc9e8ac40b..b3bd8d5db0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -36,23 +36,19 @@ import org.wso2.carbon.device.mgt.core.task.TaskOperation; import org.wso2.carbon.device.mgt.core.task.Utils; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; +import java.util.*; public class DeviceTaskManagerImpl implements DeviceTaskManager { private static Log log = LogFactory.getLog(DeviceTaskManagerImpl.class); - private static HashMap> map = new HashMap<>(); + private static Map> map = new HashMap<>(); @Override public List getOperationList() throws DeviceMgtTaskException { - - TaskConfiguration taskConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getTaskConfiguration(); + TaskConfiguration taskConfiguration = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration(); List ops = taskConfiguration.getOperations(); List taskOperations = new ArrayList<>(); @@ -68,29 +64,25 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { @Override public int getTaskFrequency() throws DeviceMgtTaskException { - - return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getTaskConfiguration().getFrequency(); + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration(). + getFrequency(); } @Override public String getTaskImplementedClazz() throws DeviceMgtTaskException { - - return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getTaskConfiguration().getTaskClazz(); + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration(). + getTaskClazz(); } @Override public boolean isTaskEnabled() throws DeviceMgtTaskException { - - return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getTaskConfiguration().isEnabled(); + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration(). + isEnabled(); } @Override public void addOperations() throws DeviceMgtTaskException { - DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(); try { @@ -98,7 +90,6 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { List operations = this.getValidOperationNames(); if (!devices.isEmpty()) { - for (String str : operations) { CommandOperation operation = new CommandOperation(); operation.setEnabled(true); @@ -116,17 +107,15 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { } catch (OperationManagementException e) { throw new DeviceMgtTaskException("Error occurred while adding the operations to devices", e); } - } @Override public List getValidOperationNames() throws DeviceMgtTaskException { - List taskOperations = this.getOperationList(); List opNames = new ArrayList<>(); Long milliseconds = System.currentTimeMillis(); int frequency = this.getTaskFrequency(); - HashMap mp = Utils.getTenantedTaskOperationMap(map); + Map mp = Utils.getTenantedTaskOperationMap(map); for (TaskOperation top : taskOperations) { if (!mp.containsKey(top.getTaskName())) { @@ -163,5 +152,6 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { return false; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java index 88acffe514..93c15914ad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java @@ -93,62 +93,91 @@ public class SearchDevice extends BaseDeviceManagementTest { } -// @Test -// public void doValidLocationSearch() throws Exception{ -// -// SearchContext context = new SearchContext(); -// List conditions = new ArrayList<>(); -// -// Condition cond = new Condition(); -// cond.setKey("LOCATION"); -// cond.setOperator("="); -// cond.setValue("Karan"); -// cond.setState(Condition.State.AND); -// conditions.add(cond); -// -// context.setConditions(conditions); -// -// SearchManagerService service = new SearchManagerServiceImpl(); -// List deviceWrappers = service.search(context); -// -// Gson gson = new Gson(); -// String bbbb = gson.toJson(deviceWrappers); -// log.info("Valid Search " + bbbb); -// -// -// for (DeviceWrapper dw : deviceWrappers) { -// log.debug(dw.getDevice().getDescription()); -// log.debug(dw.getDevice().getDeviceIdentifier()); -// } -// } -// -// @Test -// public void doInvalidLocationSearch() throws Exception{ -// -// SearchContext context = new SearchContext(); -// List conditions = new ArrayList<>(); -// -// Condition cond = new Condition(); -// cond.setKey("LOCATION"); -// cond.setOperator("="); -// cond.setValue("Colombo"); -// cond.setState(Condition.State.AND); -// conditions.add(cond); -// -// context.setConditions(conditions); -// -// SearchManagerService service = new SearchManagerServiceImpl(); -// List deviceWrappers = service.search(context); -// -// Gson gson = new Gson(); -// String bbbb = gson.toJson(deviceWrappers); -// log.info("Invalid Search " + bbbb); -// -// -// for (DeviceWrapper dw : deviceWrappers) { -// log.debug(dw.getDevice().getDescription()); -// log.debug(dw.getDevice().getDeviceIdentifier()); -// } -// } + @Test + public void doValidLocationSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Karan"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Valid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } + + @Test + public void doInvalidLocationSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Colombo"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Invalid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } + + @Test + public void doStringSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("deviceModel"); + cond.setOperator("="); + cond.setValue("SM-T520"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Invalid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java index 1e8c533d7e..67e7d2a4f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java @@ -20,8 +20,10 @@ package org.wso2.carbon.device.mgt.core; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import java.util.List; @@ -40,14 +42,6 @@ public class TestDeviceManagementService implements DeviceManagementService { return providerType; } - @Override - public String getProviderTenantDomain() { return tenantDomain;} - - @Override - public boolean isSharedWithAllTenants() { - return true; - } - @Override public void init() throws DeviceManagementException { @@ -64,9 +58,13 @@ public class TestDeviceManagementService implements DeviceManagementService { } @Override - public void notifyOperationToDevices(Operation operation, List deviceIds) - throws DeviceManagementException { + public ProvisioningConfig getProvisioningConfig() { + return new ProvisioningConfig(tenantDomain, false); + } + @Override + public PushNotificationConfig getPushNotificationConfig() { + return null; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java index 4c7996e381..36bb7c4265 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagementProviderServiceTest.java @@ -27,7 +27,6 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; -import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.common.TestDataHolder; import java.util.ArrayList; @@ -35,13 +34,11 @@ import java.util.List; public class ApplicationManagementProviderServiceTest { - private ApplicationManagementProviderService appMgtProvider; private static final Log log = LogFactory.getLog(ApplicationManagementProviderServiceTest.class); - private DeviceManagementPluginRepository deviceManagementPluginRepository = null; @BeforeClass public void init() { - deviceManagementPluginRepository = new DeviceManagementPluginRepository(); + DeviceManagementPluginRepository deviceManagementPluginRepository = new DeviceManagementPluginRepository(); TestDeviceManagementService testDeviceManagementService = new TestDeviceManagementService(TestDataHolder.TEST_DEVICE_TYPE, TestDataHolder.SUPER_TENANT_DOMAIN); try { @@ -82,8 +79,7 @@ public class ApplicationManagementProviderServiceTest { deviceId.setId(deviceIdentifier); deviceId.setType(device.getType()); - AppManagementConfig appManagementConfig = new AppManagementConfig(); - appMgtProvider = new ApplicationManagerProviderServiceImpl(); + ApplicationManagementProviderService appMgtProvider = new ApplicationManagerProviderServiceImpl(); try { appMgtProvider.updateApplicationListInstalledInDevice(deviceId, applications); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index 793fe551d9..7d6159a87f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -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) ); @@ -450,6 +451,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( ZIP VARCHAR(10) NULL, STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) @@ -476,6 +478,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) @@ -483,3 +486,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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java index 8941ad0312..dbca91f10e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java @@ -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 featureAnnotationClazz; private ClassLoader classLoader; @@ -164,7 +164,8 @@ public class AnnotationUtil { return featureList; } - private Map processParamAnnotations(Map apiParams, Method currentMethod) throws Throwable{ + private Map processParamAnnotations(Map 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 { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag new file mode 100644 index 0000000000..4d5bd9973f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -0,0 +1,87 @@ +<% +/* + * 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 uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var log = new Log("api/device-api.jag"); +var constants = require("/app/modules/constants.js"); +var utility = require("/app/modules/utility.js").utility; +var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); +var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; + +var user = session.get(constants.USER_SESSION_KEY); +var result; + +response.contentType = 'application/json'; + +if (!user) { + response.sendRedirect("/devicemgt/login?#login-required"); + exit(); +} else { + if (uriMatcher.match("/{context}/api/groups")) { + var url = request.getParameter("url"); + var draw = request.getParameter("draw"); + var length = request.getParameter("length"); + var start = request.getParameter("start"); + var search = request.getParameter("search[value]"); + var groupName = request.getParameter("columns[1][search][value]"); + var owner = request.getParameter("columns[2][search][value]"); + var targetURL; + + function appendQueryParam(url, queryParam, value) { + if (url.indexOf("?") > 0) { + return url + "&" + queryParam + "=" + value; + } + return url + "?" + queryParam + "=" + value; + } + + targetURL = devicemgtProps.httpsURL + request.getParameter("url"); + targetURL = appendQueryParam(targetURL, "start", start); + targetURL = appendQueryParam(targetURL, "length", length); + + if (search && search !== "") { + targetURL = appendQueryParam(targetURL, "search", search); + } + + if (groupName && groupName !== "") { + targetURL = appendQueryParam(targetURL, "group-name", groupName); + } + + if (owner && owner !== "") { + targetURL = appendQueryParam(targetURL, "user", owner); + } + + serviceInvokers.XMLHttp.get( + targetURL, function (responsePayload) { + response.status = 200; + result = responsePayload; + }, + function (responsePayload) { + response.status = responsePayload.status; + result = responsePayload.responseText; + }); + } +} + +if (result) { + print(result); +} + +%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index 0e4cf81077..16d01c99a8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -38,11 +38,11 @@ if (!user) { if (uriMatcher.match("/{context}/api/operations/{deviceType}/stats")) { var deviceType = uriMatcher.elements().deviceType; var deviceId = request.getParameter("deviceId"); - var monitor_operations = operationModule.getMonitorOperations(deviceType); + var monitorOperations = operationModule.getMonitorOperations(deviceType); var stats = []; result = {}; - for (var op in monitor_operations) { - result = operationModule.handleGETOperation(deviceType, monitor_operations[op].operation, monitor_operations[op].name, deviceId); + for (var op in monitorOperations) { + result = operationModule.handleGETOperation(deviceType, monitorOperations[op].operation, monitorOperations[op].name, deviceId); stats.push(result.data); } result.data = stats; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag deleted file mode 100644 index 5c8fd94355..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag +++ /dev/null @@ -1,124 +0,0 @@ -<% -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var uri = request.getRequestURI(); -var uriMatcher = new URIMatcher(String(uri)); - -var log = new Log("api/stats-api.jag"); - -var from = request.getParameter("from"); -var to = request.getParameter("to"); - -var constants = require("/app/modules/constants.js"); -var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); - -var deviceCloudGroupService = devicemgtProps["httpsURL"] + "/common/group_manager"; -var deviceCloudDeviceService = devicemgtProps["httpsURL"] + "/common/device_manager"; -var deviceCloudStatsService = devicemgtProps["httpsURL"] + "/common/stats_manager"; - -var stats = {}; -var deviceId; -var deviceType; - -var responseProcessor = require('utils').response; -response.contentType = 'application/json'; - -var user = session.get(constants.USER_SESSION_KEY); - -if (!user) { - response = responseProcessor.buildErrorResponse(response, 401, "Unauthorized"); -} else { - if (uriMatcher.match("/{context}/api/stats")) { - deviceId = request.getParameter("deviceId"); - deviceType = request.getParameter("deviceType"); - - getDeviceData(deviceType, deviceId); - - } else if (uriMatcher.match("/{context}/api/stats/group")) { - var groupId = request.getParameter("groupId"); - - //URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/all - var endPoint = deviceCloudGroupService + "/group/id/" + groupId + "/device/all"; - var data = {"username": user}; - var devices = get(endPoint, data, "json").data; - - for (var device in devices) { - deviceId = devices[device].deviceIdentifier; - deviceType = devices[device].type; - getDeviceData(deviceType, deviceId); - } - } - log.info(stats); - // returning the result. - if (stats) { - print(stats); - } -} - -function getDeviceData(deviceType, deviceId) { - //URL: GET https://localhost:9443/devicecloud/device_manager/device/type/{type}/identifier/{identifier} - var endPoint = deviceCloudDeviceService + "/device/type/" + deviceType + "/identifier/" + deviceId; - var data = {"username": user}; - var device = get(endPoint, data, "json").data; - log.info(device); - if (!device) { - return; - } - var uname = device.enrolmentInfo.owner; - - var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; - - if (analyticStreams) { - var streamTableName; - for (var stream in analyticStreams) { - streamTableName = analyticStreams[stream]["table"]; - if (stats[streamTableName] == null) { - stats[streamTableName] = []; - } - stats[streamTableName].push({ - "device": device.name, - "stats": getSensorData(streamTableName, analyticStreams[stream]["ui_unit"]["data"][1]["column"]["name"], uname, device.type, device.deviceIdentifier, from, to), - "stream": analyticStreams[stream] - }); - } - } -} - -function getSensorData(table, column, user, type, deviceIdentifier, from, to) { - - var fetchedData = []; - - try { - ///stats/device/type/{type}/identifier/{identifier} - var endPoint = deviceCloudStatsService + "/stats/device/type/" + type + "/identifier/" + deviceIdentifier; - var query = "?table=" + encodeURIComponent(table) - + "&column=" + encodeURIComponent(column) - + "&username=" + encodeURIComponent(user) - + "&from=" + from - + "&to=" + to; - endPoint = endPoint + query; - fetchedData = get(endPoint, {}, "json").data; - return fetchedData; - } catch (error) { - log.error(error); - } -} - -%> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index c2865c13b4..367db085bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -97,61 +97,6 @@ deviceModule = function () { } }; - /* - @Deprecated - */ - publicMethods.listDevicesForUser = function (username) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var devices = deviceManagementService.getDevicesOfUser(username); - var deviceList = []; - var i, device, propertiesList, deviceObject; - for (i = 0; i < devices.size(); i++) { - device = devices.get(i); - propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); - - deviceObject = {}; - deviceObject[constants.DEVICE_IDENTIFIER] = - privateMethods.validateAndReturn(device.getDeviceIdentifier()); - deviceObject[constants.DEVICE_NAME] = - privateMethods.validateAndReturn(device.getName()); - deviceObject[constants.DEVICE_OWNERSHIP] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); - deviceObject[constants.DEVICE_OWNER] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); - deviceObject[constants.DEVICE_TYPE] = - privateMethods.validateAndReturn(device.getType()); - deviceObject[constants.DEVICE_PROPERTIES] = {}; - if (device.getType() == constants.PLATFORM_IOS) { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; - } else { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); - } - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); - - deviceList.push(deviceObject); - } - return deviceList; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - /* @Deprecated */ @@ -298,8 +243,7 @@ deviceModule = function () { deviceObject[constants["DEVICE_PROPERTIES"]] = properties; return deviceObject; } - } - , + }, function (responsePayload) { var response = {}; response["status"] = "error"; @@ -314,44 +258,42 @@ 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 () { var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types"; return serviceInvokers.XMLHttp.get( url, function (responsePayload) { return responsePayload; - } - , + }, function (responsePayload) { log.error(responsePayload); return -1; @@ -383,86 +325,20 @@ deviceModule = function () { return license; }; - publicMethods.getOwnDevices = function () { - var listAllDevicesEndPoint = deviceCloudService + "/device/user/" + user.username + "/all"; - var result = get(listAllDevicesEndPoint, {}, "json"); - var devices = result.data; - var device; - for (var d in devices){ - device = devices[d]; - device.assetId = publicMethods.getAssetId(device.deviceType); - } - return result; - }; - - publicMethods.getAllPermittedDevices = function () { - var groupModule = require("/app/modules/group.js").groupModule; - - var result = publicMethods.getUnGroupedDevices(); - var unGroupedDevices = result.data; - var user_groups = groupModule.getGroups().data; - var allDevices = []; - var deviceCount = unGroupedDevices.length; - for (var g in user_groups) { - var deviceInGroup = user_groups[g].devices; - deviceCount += deviceInGroup.length; - if (deviceInGroup && deviceInGroup.length == 0) { - delete user_groups[g]["devices"]; - } - var device; - for (var d in deviceInGroup){ - device = deviceInGroup[d]; - device.assetId = publicMethods.getAssetId(device.type); - } - allDevices.push(user_groups[g]); - } - allDevices.push({id: 0, devices: unGroupedDevices}); - result.data = allDevices; - result.device_count = deviceCount; - return result; - }; - - publicMethods.removeDevice = function (deviceType, deviceId) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(deviceType); - deviceIdentifier.setId(deviceId); - return deviceManagementService.disenrollDevice(deviceIdentifier); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - publicMethods.updateDevice = function (deviceType, deviceId, deviceName) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(deviceType); - deviceIdentifier.setId(deviceId); - var device = deviceManagementService.getDevice(deviceIdentifier); - device.setName(deviceName); - return deviceManagementService.modifyEnrollment(device); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } + publicMethods.getDevices = function (userName) { + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName; + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + for (var i = 0; i < responsePayload.length; i++) { + responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type); + } + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } + ); }; - return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 37894ac2a3..31fac7176d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -20,6 +20,7 @@ var groupModule = {}; (function (groupModule) { var log = new Log("/app/modules/group.js"); + var userModule = require("/app/modules/user.js").userModule; var constants = require('/app/modules/constants.js'); var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var utility = require("/app/modules/utility.js").utility; @@ -32,12 +33,19 @@ var groupModule = {}; var endPoint; groupModule.getGroupCount = function () { - endPoint = groupServiceEndpoint + "/user/" + user.username + "/count"; + var permissions = userModule.getUIPermissions(); + if (permissions.LIST_ALL_GROUPS) { + 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; @@ -46,12 +54,11 @@ var groupModule = {}; }; groupModule.getGroupDeviceCount = function (groupName, owner) { - endPoint = groupServiceEndpoint + "/" + owner + "/" + groupName + "/devices/count"; + endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count"; return serviceInvokers.XMLHttp.get( endPoint, function (responsePayload) { return responsePayload; - } - , + }, function (responsePayload) { log.error(responsePayload); return -1; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js index 490ee8aee5..a4ee8c1256 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js @@ -67,8 +67,7 @@ policyModule = function () { policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"]; - policyObjectToView["icon"] = devicemgtProps["httpsURL"] + devicemgtProps["appContext"] + - "public/cdmf.unit.device.type." + policyObjectToView["platform"] + ".type-view/images/thumb.png"; + policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; policyObjectToView["roles"] = privateMethods. getElementsInAString(policyObjectFromRestEndpoint["roles"]); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index a26e64de9c..bca48a0362 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -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; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js index 07fbe79cc7..185c2fa029 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js @@ -18,6 +18,9 @@ var utility; utility = function () { + + var constants = require('/app/modules/constants.js'); + var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var log = new Log("/app/modules/utility.js"); var JavaClass = Packages.java.lang.Class; var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext; @@ -104,26 +107,43 @@ utility = function () { }; publicMethods.getOperationIcon = function (deviceType, operation) { - var iconPath = "/app/units/cdmf.unit.device.type." - + deviceType + ".type-view/public/images/operations/" + operation + ".png"; + var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view"); + var iconPath = "/app/units/" + unitName + "/public/images/operations/" + operation + ".png"; var icon = new File(iconPath); if (icon.isExists()) { - return "public/cdmf.unit.device.type." + deviceType + ".type-view/images/operations/" + operation + ".png"; + return devicemgtProps["appContext"] + "public/" + unitName + "/images/operations/" + operation + ".png"; } else { return null; } }; publicMethods.getDeviceThumb = function (deviceType) { - var iconPath = "/app/units/cdmf.unit.device.type." - + deviceType + ".type-view/public/images/thumb.png"; + var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view"); + var iconPath = "/app/units/" + unitName + "/public/images/thumb.png"; var icon = new File(iconPath); if (icon.isExists()) { - return "/devicemgt/public/cdmf.unit.device.type." + deviceType + ".type-view/images/thumb.png"; + return devicemgtProps["appContext"] + "public/" + unitName + "/images/thumb.png"; } else { return null; } }; + publicMethods.getTenantedDeviceUnitName = function (deviceType, unitPostfix) { + var user = session.get(constants.USER_SESSION_KEY); + if (!user) { + log.error("User object was not found in the session"); + throw constants.ERRORS.USER_NOT_FOUND; + } + var unitName = user.domain + "cdmf.unit.device.type." + deviceType + "." + unitPostfix; + if (new File("/app/units/" + unitName).isExists()) { + return unitName; + } + unitName = "cdmf.unit.device.type." + deviceType + "." + unitPostfix; + if (new File("/app/units/" + unitName).isExists()) { + return unitName; + } + return null; + }; + return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.hbs deleted file mode 100644 index 367a268ac7..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.hbs +++ /dev/null @@ -1,42 +0,0 @@ -{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}} -{{unit "cdmf.unit.ui.content.title" pageHeader=title}} - -{{#zone "breadcrumbs"}} -
  • - - - -
  • - {{#if groupName}} -
  • - - Groups - -
  • -
  • - - {{groupName}} - -
  • - {{else}} -
  • - - Devices - -
  • -
  • - - {{deviceName}} - -
  • - {{/if}} -
  • - - Analytics - -
  • -{{/zone}} - -{{#zone "content"}} - {{unit "cdmf.unit.analytics"}} -{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js index bb2c02374e..82aa1101a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js @@ -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.hbs new file mode 100644 index 0000000000..d03feccbd3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.hbs @@ -0,0 +1,89 @@ +{{#zone "topCss"}} + {{css "css/analytics.css"}} + {{css "css/daterangepicker.css"}} + {{css "css/graph.css"}} +{{/zone}} + +{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}} +{{unit "cdmf.unit.ui.content.title" pageHeader=title}} +{{unit "cdmf.unit.lib.service-invoker-utility"}} +{{unit "cdmf.unit.lib.handlebars"}} + +{{#zone "breadcrumbs"}} +
  • + + + +
  • + {{#if groupName}} +
  • + + Groups + +
  • +
  • + + {{groupName}} + +
  • + {{else}} +
  • + + Devices + +
  • +
  • + + {{deviceName}} + +
  • + {{/if}} +
  • + + Analytics + +
  • +{{/zone}} + +{{#zone "content"}} +
    +
    +
    +
    +

    {{deviceName}} Analytics

    +
    +
    +
    +
    + + + + + +
    +
    +
    +
    +
    +
    +
    + {{unit deviceAnalyticsViewUnitName}} +
    +
    +
    +{{/zone}} +{{#zone "bottomJs"}} + {{js "js/jquery.daterangepicker.js"}} + {{js "js/graph_util.js"}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js similarity index 65% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js index f278f9b512..4b11b91aa1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.js @@ -17,11 +17,22 @@ */ function onRequest(context) { + 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 = request.getParameter("deviceType"); + var deviceType = context.uriParams.deviceType; var title = "Analytics"; if (groupName) { title = "Group " + title; @@ -29,11 +40,12 @@ function onRequest(context) { title = "Device " + title; } return { + "deviceAnalyticsViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "analytics-view"), + "deviceType": deviceType, "title": title, "groupName": groupName, "groupId": groupId, "deviceName": deviceName, - "deviceId": deviceId, - "deviceType": deviceType + "deviceId": deviceId }; -} \ No newline at end of file +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.json similarity index 56% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.json rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.json index c8a14cad93..846ee092b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.analytics/analytics.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/analytics.json @@ -1,5 +1,5 @@ { "version": "1.0.0", - "uri": "/analytics", + "uri": "/device/{deviceType}/analytics", "layout": "cdmf.layout.default" } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/analytics.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/analytics.css similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/analytics.css rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/analytics.css diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/daterangepicker.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/daterangepicker.css similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/daterangepicker.css rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/daterangepicker.css diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/graph.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/graph.css similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/css/graph.css rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/css/graph.css diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/graph_util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/graph_util.js new file mode 100644 index 0000000000..c8171b5bf2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/graph_util.js @@ -0,0 +1,98 @@ +/* + * 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()); + +function initDate() { + currentDay = new Date(); +} + +var DateRange = convertDate(startDate) + " to " + convertDate(endDate); + +$(document).ready(function () { + initDate(); + + $('#date-range').html(DateRange); + $('#date-range').dateRangePicker() + .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; + drawGraph(fromDate, toDate); + } + ); + setDateTime(currentDay.getTime() - 3600000, currentDay.getTime()); + $('#hour-btn').addClass('active'); +}); + +//hour +$('#hour-btn').on('click', function () { + initDate(); + setDateTime(currentDay.getTime() - 3600000, currentDay.getTime()); +}); + +//12 hours +$('#h12-btn').on('click', function () { + initDate(); + setDateTime(currentDay.getTime() - (3600000 * 12), currentDay.getTime()); +}); + +//24 hours +$('#h24-btn').on('click', function () { + initDate(); + setDateTime(currentDay.getTime() - (3600000 * 24), currentDay.getTime()); +}); + +//48 hours +$('#h48-btn').on('click', function () { + initDate(); + setDateTime(currentDay.getTime() - (3600000 * 48), currentDay.getTime()); +}); + +$('body').on('click', '.btn-group button', function (e) { + $(this).addClass('active'); + $(this).siblings().removeClass('active'); +}); + +function setDateTime(from, to) { + fromDate = from; + toDate = to; + startDate = new Date(from); + endDate = new Date(to); + DateRange = convertDate(startDate) + " to " + convertDate(endDate); + $('#date-range').html(DateRange); + var tzOffset = new Date().getTimezoneOffset() * 60 / 1000; + from += tzOffset; + to += tzOffset; + + // the relevant import units needs to implement this. + drawGraph(parseInt(from / 1000), parseInt(to / 1000)); +} + +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; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/js/jquery-ui-timepicker-addon.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/jquery-ui-timepicker-addon.js similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/js/jquery-ui-timepicker-addon.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/jquery-ui-timepicker-addon.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/js/jquery.daterangepicker.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/jquery.daterangepicker.js similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.analytics/public/js/jquery.daterangepicker.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.analytics/public/js/jquery.daterangepicker.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js index 517c375afe..693769dd11 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.type.view/view.js @@ -39,9 +39,8 @@ function onRequest(context) { } return { - "deviceTypeViewUnitName": "cdmf.unit.device.type." + deviceType + ".type-view", + "deviceTypeViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "type-view"), "deviceType": deviceType, "label" : configs["deviceType"]["label"] }; } - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js index 54200bef94..21ce993020 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.device.view/view.js @@ -17,6 +17,7 @@ */ function onRequest(context){ + 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"); @@ -28,6 +29,5 @@ function onRequest(context){ }); var deviceType = context.uriParams.deviceType; - - return {"deviceViewUnitName" : "cdmf.unit.device.type." + deviceType + ".device-view"}; -} \ No newline at end of file + return {"deviceViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "device-view")}; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index 20edeaf190..b800c8777e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -55,6 +55,11 @@ {{/zone}} {{#zone "content"}} +
    +
    + {{title}} +
    +
    @@ -100,18 +105,19 @@ - - - -
    -

    Enabling Device Operations

    -

    To enable device operations, select the desired platform from above - filter.

    -
    - - + + + + + + + + + + + + + @@ -274,7 +280,7 @@