diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml index 4c32e6f2ae..aeb8e0168c 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -22,13 +22,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.annotations - 4.1.16-SNAPSHOT bundle WSO2 Carbon - API Management Annotations WSO2 Carbon - API Management Custom Annotation Module @@ -73,8 +72,8 @@ org.wso2.carbon.apimgt.annotations.* - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.servlet, javax.xml.*, diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index a77543fc93..6b0a02043b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -21,12 +21,11 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 - 4.1.16-SNAPSHOT org.wso2.carbon.apimgt.application.extension.api war WSO2 Carbon - API Application Management API @@ -34,42 +33,24 @@ http://wso2.org - - org.apache.cxf - cxf-rt-frontend-jaxws + io.swagger + swagger-annotations + + + org.springframework + spring-web provided org.apache.cxf - cxf-rt-frontend-jaxrs + cxf-bundle-jaxrs provided - - org.apache.cxf - cxf-rt-transports-http - provided - - - - - org.codehaus.jackson - jackson-core-asl - org.codehaus.jackson jackson-jaxrs - - javax - javaee-web-api - provided - - - javax.ws.rs - jsr311-api - provided - commons-httpclient.wso2 commons-httpclient diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index aec0df4a16..702db64527 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -27,8 +27,6 @@ import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor; -import org.wso2.carbon.apimgt.integration.client.store.StoreClient; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; @@ -110,12 +108,10 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi if (username.equals(registrationProfile.getUsername())) { synchronized (ApiApplicationRegistrationServiceImpl.class) { - StoreClient storeClient = new StoreClient(new OAuthRequestInterceptor(registrationProfile.getUsername(), - registrationProfile.getPassword())); ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, - registrationProfile.isAllowedToAllDomains(), validityPeriod, storeClient); + registrationProfile.isAllowedToAllDomains(), validityPeriod); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/filter/ApiPermissionFilter.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/filter/ApiPermissionFilter.java index 0c78488a2d..fc3efadb42 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/filter/ApiPermissionFilter.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/filter/ApiPermissionFilter.java @@ -25,7 +25,12 @@ import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import javax.servlet.*; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml index b410b42670..5cb6aa6282 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml index a04bf65bb9..ae6c1076a2 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml @@ -22,12 +22,11 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 - 4.1.16-SNAPSHOT org.wso2.carbon.apimgt.application.extension bundle WSO2 Carbon - API Application Management @@ -51,14 +50,15 @@ org.wso2.carbon org.wso2.carbon.logging - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.client - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.generated.client - + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + provided + com.googlecode.json-simple.wso2 json-simple @@ -100,24 +100,32 @@ ${carbon.device.mgt.version} API Management Application Bundle org.wso2.carbon.apimgt.application.extension.internal - - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging.*, - org.wso2.carbon.user.core.*, - org.wso2.carbon.user.api, - org.wso2.carbon.utils.multitenancy, + + org.apache.commons.lang;version="[2.6,3)", + org.apache.commons.logging;version="[1.2,2)", org.json.simple, - org.wso2.carbon.context, - org.wso2.carbon.base, - org.wso2.carbon.registry.core.*;resolution:=optional, - org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", - org.wso2.carbon.apimgt.integration.client.*, - org.wso2.carbon.apimgt.integration.generated.client.store.api, - org.wso2.carbon.apimgt.integration.generated.client.store.model, - org.wso2.carbon.identity.jwt.client.extension.*, - feign - + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.api.dto;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.application.extension.bean, + org.wso2.carbon.apimgt.application.extension.dto, + org.wso2.carbon.apimgt.application.extension.exception, + org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.apimgt.impl.utils;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.context;version="${carbon.kernel.version.range}", + org.wso2.carbon.identity.jwt.client.extension, + org.wso2.carbon.identity.jwt.client.extension.dto, + org.wso2.carbon.identity.jwt.client.extension.exception, + org.wso2.carbon.identity.jwt.client.extension.service, + org.wso2.carbon.registry.core.exceptions;version="[1.0,2)", + org.wso2.carbon.registry.core.service;version="[1.0,2)", + org.wso2.carbon.registry.indexing.service;version="${carbon.registry.imp.pkg.version.range}", + org.wso2.carbon.user.api;version="[1.0,2)", + org.wso2.carbon.user.core.service;version="${carbon.kernel.version.range}", + org.wso2.carbon.user.core.tenant;version="${carbon.kernel.version.range}" + !org.wso2.carbon.apimgt.application.extension.internal, org.wso2.carbon.apimgt.application.extension.* diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java index 62d353d0fd..7405737237 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java @@ -20,7 +20,6 @@ package org.wso2.carbon.apimgt.application.extension; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.apimgt.integration.client.store.StoreClient; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; /** @@ -51,28 +50,6 @@ public interface APIManagementProviderService { String keyType, String username, boolean isAllowedAllDomains, String validityTime) throws APIManagerException; - /** - * Generate and retreive application keys. if the application does exist then - * create it and subscribe to apis that are grouped with the tags. - * - * @param apiApplicationName name of the application. - * @param tags tags of the apis that application needs to be subscribed. - * @param keyType of the application. - * @param username to whom the application is created - * @param isAllowedAllDomains application is allowed to all the tenants - * @param validityTime validity period of the application - * @param storeClient Specified store client - * @return consumerkey and secrete of the created application. - * @throws APIManagerException - */ - ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, - String tags[], - String keyType, - String username, - boolean isAllowedAllDomains, - String validityTime, - StoreClient storeClient) throws APIManagerException; - /** * Remove APIM Application. */ diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java index 0c957fd4e7..99dde8d4b3 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -18,18 +18,29 @@ package org.wso2.carbon.apimgt.application.extension; -import feign.FeignException; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIAdmin; +import org.wso2.carbon.apimgt.api.APIConsumer; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIKey; +import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; +import org.wso2.carbon.apimgt.api.model.Application; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.api.model.Subscriber; import org.wso2.carbon.apimgt.application.extension.bean.APIRegistrationProfile; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil; -import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor; -import org.wso2.carbon.apimgt.integration.client.store.StoreClient; -import org.wso2.carbon.apimgt.integration.generated.client.store.model.*; +import org.wso2.carbon.apimgt.impl.APIAdminImpl; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerFactory; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; @@ -39,7 +50,10 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; /** * This class represents an implementation of APIManagementProviderService. @@ -47,51 +61,37 @@ import java.util.List; public class APIManagementProviderServiceImpl implements APIManagementProviderService { private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); - private static final String CONTENT_TYPE = "application/json"; - private static final int MAX_API_PER_TAG = 200; - private static final String APP_TIER_TYPE = "application"; + public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); + @Override public boolean isTierLoaded() { - StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() - .getStoreClient(); - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getTenantDomain(); + + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + try { - storeClient.getIndividualTier().tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER, - APP_TIER_TYPE, - tenantDomain, CONTENT_TYPE, null, null); + APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, tenantDomain); return true; - } catch (FeignException e) { - log.error("Feign Exception", e); - if (e.status() == 401) { - OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor(); - String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - oAuthRequestInterceptor.removeToken(username, tenantDomain); - try { - storeClient.getIndividualTier().tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER, - APP_TIER_TYPE, tenantDomain, CONTENT_TYPE, null, null); - } catch (FeignException ex) { - log.error("Invalid Attempt : " + ex); - } - } - } catch (Exception e) { + } catch (APIManagementException e) { log.error("APIs not ready", e); } + return false; } @Override public void removeAPIApplication(String applicationName, String username) throws APIManagerException { - StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() - .getStoreClient(); - ApplicationList applicationList = storeClient.getApplications() - .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); - if (applicationList.getList() != null && applicationList.getList().size() > 0) { - ApplicationInfo applicationInfo = applicationList.getList().get(0); - storeClient.getIndividualApplication().applicationsApplicationIdDelete(applicationInfo.getApplicationId(), - null, null); + try { + APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); + Application application = apiConsumer.getApplicationsByName(username, applicationName, ""); + if (application != null) { + apiConsumer.removeApplication(application, username); + } + } catch (APIManagementException e) { + throw new APIManagerException("Failed to remove api application : " + applicationName, e); } + + } /** @@ -99,95 +99,83 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe */ @Override public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], - String keyType, String username, - boolean isAllowedAllDomains, String validityTime, - StoreClient sClient) throws APIManagerException { + String keyType, String username, boolean isAllowedAllDomains, String validityTime) + throws APIManagerException { - StoreClient storeClient; - - if (sClient == null) { - storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() - .getStoreClient(); - } else { - storeClient = sClient; + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + if (StringUtils.isEmpty(username)) { + username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); } - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getTenantDomain(); try { - ApplicationList applicationList = storeClient.getApplications() - .applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); - Application application; - if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) { - //create application; - application = new Application(); - application.setName(applicationName); - application.setSubscriber(username); - application.setDescription(""); - application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER); - application.setGroupId(""); - application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE); - } else { - ApplicationInfo applicationInfo = applicationList.getList().get(0); - application = storeClient.getIndividualApplication() - .applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null); - } + APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); + Application application = apiConsumer.getApplicationsByName(username, applicationName, ""); + + int applicationId = 0; + Subscriber subscriber = null; if (application == null) { - throw new APIManagerException( - "Api application creation failed for " + applicationName + " to the user " + username); + subscriber = apiConsumer.getSubscriber(username); + if (subscriber == null) { + // create subscriber + apiConsumer.addSubscriber(username, ""); + subscriber = apiConsumer.getSubscriber(username); + } + //create application + application = new Application(applicationName, subscriber); + application.setTier(ApiApplicationConstants.DEFAULT_TIER); + application.setGroupId(""); + application.setTokenType("OAUTH"); + apiConsumer.addApplication(application, username); + application = apiConsumer.getApplicationsByName(username, applicationName, ""); + } else { + subscriber = apiConsumer.getSubscriber(username); } - SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet - (null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null); - List needToSubscribe = new ArrayList<>(); + Set subscribedAPIs = + apiConsumer.getSubscribedAPIs(subscriber, applicationName, ""); + + log.info("Already subscribed API count: " + subscribedAPIs.size()); + // subscribe to apis. + Set tempApiIds = new HashSet<>(); if (tags != null && tags.length > 0) { for (String tag : tags) { - APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag - , CONTENT_TYPE, null); - if (apiList.getList() == null || apiList.getList().size() == 0) { - apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0 - , MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null); + Set apisWithTag = apiConsumer.getAPIsWithTag(tag, tenantDomain); + if (apisWithTag == null || apisWithTag.size() == 0) { + apisWithTag = apiConsumer.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); } - if (apiList.getList() != null && apiList.getList().size() > 0) { - for (APIInfo apiInfo : apiList.getList()) { - String id = apiInfo.getProvider().replace("@", "-AT-") - + "-" + apiInfo.getName() + "-" + apiInfo.getVersion(); - id = id.replace(" ", "+"); + if (apisWithTag != null && apisWithTag.size() > 0) { + for (API apiInfo : apisWithTag) { + String id = apiInfo.getId().getProviderName().replace("@", "-AT-") + + "-" + apiInfo.getId().getName() + "-" + apiInfo.getId().getVersion(); + // todo: amalka will this break old apis? boolean subscriptionExist = false; - if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) { - for (Subscription subs : subscriptionList.getList()) { - if (subs.getApiIdentifier().equals(id)) { + if (subscribedAPIs.size() > 0) { + for (SubscribedAPI subscribedAPI : subscribedAPIs) { + if (String.valueOf(subscribedAPI.getApiId().toString()).equals(id)) { subscriptionExist = true; break; } } } - if (!subscriptionExist) { - Subscription subscription = new Subscription(); - //fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0 + if (!subscriptionExist && !tempApiIds.contains(id)) { + ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID( + apiInfo.getUuid(), tenantDomain); + apiTypeWrapper.setTier(ApiApplicationConstants.DEFAULT_TIER); - subscription.setApiIdentifier(id); - subscription.setApplicationId(application.getApplicationId()); - subscription.tier(ApiApplicationConstants.DEFAULT_TIER); - if (!needToSubscribe.contains(subscription)) { - needToSubscribe.add(subscription); - } + apiConsumer.addSubscription(apiTypeWrapper, username, application); + tempApiIds.add(id); } } } } } - if (!needToSubscribe.isEmpty()) { - storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE); - } //end of subscription - List applicationKeys = application.getKeys(); + List applicationKeys = application.getKeys(); if (applicationKeys != null) { - for (ApplicationKey applicationKey : applicationKeys) { - if (keyType.equals(applicationKey.getKeyType().toString())) { + for (APIKey applicationKey : applicationKeys) { + if (keyType.equals(applicationKey.getType())) { if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); @@ -198,45 +186,51 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } } - ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest(); List allowedDomains = new ArrayList<>(); if (isAllowedAllDomains) { allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); } else { allowedDomains.add(APIManagerUtil.getTenantDomain()); } - applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains); - applicationKeyGenerateRequest.setCallbackUrl(""); - applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION); - applicationKeyGenerateRequest.setValidityTime(validityTime); - ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost( - application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null); - if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); - apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); - return apiApplicationKey; + APIAdmin apiAdmin = new APIAdminImpl(); + String keyManagerId = null; + try { + List keyManagerConfigurations = apiAdmin + .getKeyManagerConfigurationsByTenant(tenantDomain); + if (keyManagerConfigurations != null) { + for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurations) { + keyManagerId = keyManagerConfigurationDTO.getUuid(); + } + } + String jsonString = "{\"grant_types\":\"refresh_token,urn:ietf:params:oauth:grant-type:saml2-bearer," + + "password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," + + "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," + + "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," + + "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + + "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + + "\"username\":\"" + username + "\"}"; + + Map keyDetails = apiConsumer + .requestApprovalForApplicationRegistration(username, applicationName, keyType, "", + allowedDomains.toArray(new String[allowedDomains.size()]), validityTime, "default", "", + jsonString, keyManagerId, tenantDomain); + + if (keyDetails != null) { + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey((String) keyDetails.get("consumerKey")); + apiApplicationKey.setConsumerSecret((String) keyDetails.get("consumerSecret")); + return apiApplicationKey; + } + throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain); + } catch (APIManagementException e) { + throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); } - throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain); - } catch (FeignException e) { + } catch (APIManagementException e) { throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); } } - /** - * {@inheritDoc} - */ - @Override - public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], - String keyType, String username, - boolean isAllowedAllDomains, - String validityTime) - throws APIManagerException { - return this.generateAndRetrieveApplicationKeys(applicationName, tags, keyType, username, - isAllowedAllDomains, validityTime, null); - } - @Override public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, String validityPeriod) throws APIManagerException { @@ -311,7 +305,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) { info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), - registrationProfile.getTags(), tokenType, registrationProfile.getApplicationName(), + registrationProfile.getTags(), tokenType, null, registrationProfile.isAllowedToAllDomains(), validityPeriod); } } finally { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java index 90f297e6d3..26f0320974 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java @@ -18,7 +18,6 @@ package org.wso2.carbon.apimgt.application.extension.internal; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; @@ -35,7 +34,6 @@ public class APIApplicationManagerExtensionDataHolder { private TenantManager tenantManager; private TenantRegistryLoader tenantRegistryLoader; private TenantIndexingLoader indexLoader; - private IntegrationClientService integrationClientService; private JWTClientManagerService jwtClientManagerService; private APIApplicationManagerExtensionDataHolder() { @@ -94,15 +92,6 @@ public class APIApplicationManagerExtensionDataHolder { return indexLoader; } - public IntegrationClientService getIntegrationClientService() { - return integrationClientService; - } - - public void setIntegrationClientService( - IntegrationClientService integrationClientService) { - this.integrationClientService = integrationClientService; - } - public JWTClientManagerService getJwtClientManagerService() { if (jwtClientManagerService == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java index 9d28c89f16..d2c675c253 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java @@ -23,7 +23,6 @@ import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext;; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.user.core.service.RealmService; @@ -49,12 +48,6 @@ import org.wso2.carbon.user.core.service.RealmService; * policy="dynamic" * bind="setRealmService" * unbind="unsetRealmService" - * @scr.reference name="integration.client.service" - * interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService" - * cardinality="1..1" - * policy="dynamic" - * bind="setIntegrationClientService" - * unbind="unsetIntegrationClientService" */ public class APIApplicationManagerExtensionServiceComponent { @@ -97,17 +90,6 @@ public class APIApplicationManagerExtensionServiceComponent { APIApplicationManagerExtensionDataHolder.getInstance().setIndexLoaderService(null); } - protected void setIntegrationClientService(IntegrationClientService integrationClientService) { - if (integrationClientService != null && log.isDebugEnabled()) { - log.debug("integrationClientService initialized"); - } - APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(integrationClientService); - } - - protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) { - APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(null); - } - /** * Sets Realm Service. * diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml index 2fbd10211f..aa77bf7ecd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.handlers/pom.xml @@ -21,13 +21,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handlers - 4.1.16-SNAPSHOT bundle WSO2 Carbon - API Security Handler Component WSO2 Carbon - API Management Security Handler Module diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml index eeddf628a5..7980d20223 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/pom.xml @@ -13,13 +13,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client - 4.1.16-SNAPSHOT bundle WSO2 Carbon - API Management Integration Client WSO2 Carbon - API Management Integration Client diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml index 22c399e5b7..391979285e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.generated.client/pom.xml @@ -13,13 +13,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.generated.client - 4.1.16-SNAPSHOT bundle WSO2 Carbon - API Management Integration Generated Client WSO2 Carbon - API Management Integration Client diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index f033de1d89..1934338712 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -22,13 +22,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher - 4.1.16-SNAPSHOT bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher @@ -109,8 +108,14 @@ org.wso2.carbon.device.mgt.common - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.client + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + provided + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + provided com.h2database.wso2 @@ -144,41 +149,46 @@ org.wso2.carbon.apimgt.webapp.publisher.* - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging, - javax.servlet, - javax.xml.*, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - com.google.gson.*, - org.apache.catalina, - org.apache.catalina.core, - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.wso2.carbon.core, - org.apache.commons.lang, - org.wso2.carbon.utils, - org.wso2.carbon.apimgt.annotations.*, - org.wso2.carbon.governance.lcm.util.*, - org.wso2.carbon.registry.core.*, + com.google.gson;version="2.3", + com.google.gson.reflect;version="2.3", io.swagger.annotations, - javax.net.ssl, - org.scannotation, - org.scannotation.archiveiterator, + javax.servlet;version="2.6", + javax.xml, + javax.xml.bind, + javax.xml.bind.annotation, + javax.xml.parsers, + org.apache.catalina;version="9.0", + org.apache.catalina.core;version="9.0", + org.apache.commons.logging;version="1.2", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", + org.scannotation;version="1.0", + org.scannotation.archiveiterator;version="1.0", org.w3c.dom, - org.wso2.carbon.apimgt.integration.client.*, - org.wso2.carbon.context, - org.wso2.carbon.core.util, - org.wso2.carbon.user.api, - org.wso2.carbon.user.core.*, - org.wso2.carbon.utils.multitenancy, - org.wso2.carbon.apimgt.integration.generated.client.publisher.api, - org.wso2.carbon.apimgt.integration.generated.client.publisher.model + org.wso2.carbon.apimgt.annotations.api, + org.wso2.carbon.apimgt.api, + org.wso2.carbon.apimgt.api.model, + org.wso2.carbon.apimgt.impl, + org.wso2.carbon.apimgt.webapp.publisher, + org.wso2.carbon.apimgt.webapp.publisher.config, + org.wso2.carbon.apimgt.webapp.publisher.dto, + org.wso2.carbon.apimgt.webapp.publisher.exception, + org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener, + org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util, + org.wso2.carbon.base;version="1.0", + org.wso2.carbon.context;version="4.6", + org.wso2.carbon.core;version="4.6", + org.wso2.carbon.core.util;version="4.6", + org.wso2.carbon.registry.core.service;version="1.0", + org.wso2.carbon.user.api;version="1.0", + org.wso2.carbon.user.core.service;version="4.6", + org.wso2.carbon.user.core.tenant;version="4.6", + org.wso2.carbon.utils;version="4.6", + org.wso2.carbon.utils.multitenancy;version="4.6" - javax.ws.rs-api, - scribe;scope=compile|runtime;inline=false; + jsr311-api;scope=compile|runtime;inline=false - * @@ -210,4 +220,5 @@ + 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 2fe35e472b..b1c7769768 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,15 +18,31 @@ */ package org.wso2.carbon.apimgt.webapp.publisher; -import feign.FeignException; -import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.*; -import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; +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.APIRevision; +import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; +import org.wso2.carbon.apimgt.api.model.CORSConfiguration; +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.Tier; +import org.wso2.carbon.apimgt.api.model.URITemplate; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; +import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; -import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import java.util.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; /** * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all @@ -34,11 +50,10 @@ import java.util.*; */ public class APIPublisherServiceImpl implements APIPublisherService { private static final String UNLIMITED_TIER = "Unlimited"; - private static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox"; - private static final String CONTENT_TYPE = "application/json"; - private static final String PUBLISHED_STATUS = "PUBLISHED"; + private static final String API_PUBLISH_ENVIRONMENT = "Default"; private static final String CREATED_STATUS = "CREATED"; private static final String PUBLISH_ACTION = "Publish"; + public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); @Override public void publishAPI(APIConfig apiConfig) throws APIManagerPublisherException { @@ -47,99 +62,124 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner()); try { - PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService() - .getPublisherClient(); + APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(apiConfig.getOwner()); API api = getAPI(apiConfig); - APIList apiList = publisherClient.getApis().apisGet(100, 0, "name:" + api.getName(), CONTENT_TYPE, null); - if (!isExist(api, apiList)) { - api = publisherClient.getApi().apisPost(api, CONTENT_TYPE, null); - if (CREATED_STATUS.equals(api.getStatus())) { - publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, null); + if (!apiProvider.isAPIAvailable(api.getId())) { + API createdAPI = apiProvider.addAPI(api); + if (CREATED_STATUS.equals(createdAPI.getStatus())) { + apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); + APIRevision apiRevision = new APIRevision(); + apiRevision.setApiUUID(createdAPI.getUuid()); + apiRevision.setDescription("Initial Revision"); + String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); + APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); + apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); + apiRevisionDeployment.setVhost("localhost"); + apiRevisionDeployment.setDisplayOnDevportal(true); + + List apiRevisionDeploymentList = new ArrayList<>(); + apiRevisionDeploymentList.add(apiRevisionDeployment); + apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); + } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { - for (APIInfo apiInfo : apiList.getList()) { - if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) { - api = publisherClient.getApi().apisApiIdPut(apiInfo.getId(), api, CONTENT_TYPE, null, null); - if (api != null && CREATED_STATUS.equals(api.getStatus())) { - publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, - null); - } + API existingAPI = apiProvider.getAPI(api.getId()); + api.setStatus(existingAPI.getStatus()); + apiProvider.updateAPI(api); + if (api.getId().getName().equals(existingAPI.getId().getName()) && + api.getId().getVersion().equals(existingAPI.getId().getVersion())) { + if (CREATED_STATUS.equals(existingAPI.getStatus())) { + apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); } - } } } - } catch (FeignException e) { + + + } catch (FaultGatewaysException | APIManagementException e) { throw new APIManagerPublisherException(e); } finally { PrivilegedCarbonContext.endTenantFlow(); } } - private boolean isExist(API api, APIList apiList) { - if (apiList == null || apiList.getList() == null || apiList.getList().size() == 0) { - return false; - } - for (APIInfo existingApi : apiList.getList()) { - if (existingApi.getName() != null && existingApi.getName().equals(api. - getName()) && existingApi.getVersion() != null && - existingApi.getVersion().equals(api.getVersion())) { - return true; - } - } - return false; - } - private API getAPI(APIConfig config) { - API api = new API(); - api.setName(config.getName()); + APIIdentifier apiIdentifier = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion()); + API api = new API(apiIdentifier); api.setDescription(""); - String context = config.getContext(); context = context.startsWith("/") ? context : ("/" + context); - api.setContext(context); - api.setVersion(config.getVersion()); - api.setProvider(config.getOwner()); - api.setApiDefinition(APIPublisherUtil.getSwaggerDefinition(config)); - api.setWsdlUri(null); - api.setStatus(PUBLISHED_STATUS); - api.setResponseCaching("DISABLED"); - api.setDestinationStatsEnabled("false"); - api.isDefaultVersion(config.isDefault()); - List transport = new ArrayList<>(); - transport.add("https"); - transport.add("http"); - api.transport(transport); - api.setTags(Arrays.asList(config.getTags())); - api.addTiersItem(UNLIMITED_TIER); - api.setGatewayEnvironments(API_PUBLISH_ENVIRONMENT); - if (config.isSharedWithAllTenants()) { - api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.all_tenants); - api.setVisibility(API.VisibilityEnum.PUBLIC); - } else { - api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.current_tenant); - api.setVisibility(API.VisibilityEnum.PRIVATE); - } - String endpointConfig = "{\"production_endpoints\":{\"url\":\"" + config.getEndpoint() + - "\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}"; + api.setContext(context + "/" + config.getVersion()); + api.setStatus(CREATED_STATUS); + api.setWsdlUrl(null); + api.setResponseCache("Disabled"); + api.setContextTemplate(context + "/{version}" ); + api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config)); + api.setType("HTTP"); + Set uriTemplates = new HashSet<>(); + Iterator iterator; + for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { + ApiUriTemplate apiUriTemplate = iterator.next(); + URITemplate uriTemplate = new URITemplate(); + uriTemplate.setAuthType(apiUriTemplate.getAuthType()); + uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb()); + uriTemplate.setResourceURI(apiUriTemplate.getResourceURI()); + uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate()); + Scope scope = new Scope(); + if (apiUriTemplate.getScope() != null) { + scope.setName(apiUriTemplate.getScope().getName()); + scope.setDescription(apiUriTemplate.getScope().getDescription()); + scope.setKey(apiUriTemplate.getScope().getKey()); + scope.setRoles(apiUriTemplate.getScope().getRoles()); + uriTemplate.setScope(scope); + } + uriTemplates.add(uriTemplate); + } + api.setUriTemplates(uriTemplates); + + api.setApiOwner(config.getOwner()); + + + api.setDefaultVersion(config.isDefault()); + api.setTransports("https,http"); + + Set tags = new HashSet<>(); + tags.addAll(Arrays.asList(config.getTags())); + api.setTags(tags); + + Set availableTiers = new HashSet<>(); + availableTiers.add(new Tier(UNLIMITED_TIER)); + api.setAvailableTiers(availableTiers); + + Set environments = new HashSet<>(); + environments.add(API_PUBLISH_ENVIRONMENT); + api.setEnvironments(environments); + + if (config.isSharedWithAllTenants()) { + api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS); + api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); + } else { + api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT); + api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY); + } + String endpointConfig = "{ \"endpoint_type\": \"http\", \"sandbox_endpoints\": { \"url\": \" " + + config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" "+ config.getEndpoint()+"\" } }"; api.setEndpointConfig(endpointConfig); - APICorsConfiguration apiCorsConfiguration = new APICorsConfiguration(); List accessControlAllowOrigins = new ArrayList<>(); accessControlAllowOrigins.add("*"); - apiCorsConfiguration.setAccessControlAllowOrigins(accessControlAllowOrigins); List accessControlAllowHeaders = new ArrayList<>(); accessControlAllowHeaders.add("authorization"); accessControlAllowHeaders.add("Access-Control-Allow-Origin"); accessControlAllowHeaders.add("Content-Type"); accessControlAllowHeaders.add("SOAPAction"); - apiCorsConfiguration.setAccessControlAllowHeaders(accessControlAllowHeaders); - + accessControlAllowHeaders.add("apikey"); + accessControlAllowHeaders.add("Internal-Key"); List accessControlAllowMethods = new ArrayList<>(); accessControlAllowMethods.add("GET"); accessControlAllowMethods.add("PUT"); @@ -147,10 +187,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessControlAllowMethods.add("POST"); accessControlAllowMethods.add("PATCH"); accessControlAllowMethods.add("OPTIONS"); - apiCorsConfiguration.setAccessControlAllowMethods(accessControlAllowMethods); - apiCorsConfiguration.setAccessControlAllowCredentials(false); - apiCorsConfiguration.corsConfigurationEnabled(false); - api.setCorsConfiguration(apiCorsConfiguration); + CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false, + accessControlAllowHeaders, accessControlAllowMethods); + api.setCorsConfiguration(corsConfiguration); + + api.setAuthorizationHeader("Authorization"); + List keyManagers = new ArrayList<>(); + keyManagers.add("all"); + api.setKeyManagers(keyManagers); + api.setEnableStore(true); + return api; } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index 639c2fe217..afc5ec6998 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -18,7 +18,6 @@ */ package org.wso2.carbon.apimgt.webapp.publisher.internal; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.registry.core.service.RegistryService; @@ -37,8 +36,6 @@ public class APIPublisherDataHolder { private RegistryService registryService; private boolean isServerStarted; private Stack unpublishedApis = new Stack<>(); - private IntegrationClientService integrationClientService; - private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private APIPublisherDataHolder() { @@ -117,12 +114,4 @@ public class APIPublisherDataHolder { this.unpublishedApis = unpublishedApis; } - public IntegrationClientService getIntegrationClientService() { - return integrationClientService; - } - - public void setIntegrationClientService( - IntegrationClientService integrationClientService) { - this.integrationClientService = integrationClientService; - } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index dd5736570c..dbdd874810 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -22,7 +22,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherStartupHandler; @@ -45,11 +44,6 @@ import org.wso2.carbon.user.core.service.RealmService; * policy="dynamic" * bind="setRegistryService" * unbind="unsetRegistryService" - * interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService" - * cardinality="1..1" - * policy="dynamic" - * bind="setIntegrationClientService" - * unbind="unsetIntegrationClientService" */ public class APIPublisherServiceComponent { @@ -120,14 +114,4 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRegistryService(null); } - protected void setIntegrationClientService(IntegrationClientService integrationClientService) { - if (integrationClientService != null && log.isDebugEnabled()) { - log.debug("integrationClientService initialized"); - } - APIPublisherDataHolder.getInstance().setIntegrationClientService(integrationClientService); - } - - protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) { - APIPublisherDataHolder.getInstance().setIntegrationClientService(null); - } } diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 41507f9fa9..a692fbbf24 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,25 +22,21 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 apimgt-extensions - 4.1.16-SNAPSHOT pom WSO2 Carbon - API Management Extensions Component http://wso2.org - org.wso2.carbon.apimgt.integration.generated.client - org.wso2.carbon.apimgt.integration.client org.wso2.carbon.apimgt.webapp.publisher org.wso2.carbon.apimgt.application.extension org.wso2.carbon.apimgt.application.extension.api org.wso2.carbon.apimgt.annotations - org.wso2.carbon.apimgt.handlers diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.addons/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.addons/pom.xml index e85664237d..059af5fb7e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.addons/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.addons/pom.xml @@ -3,13 +3,12 @@ application-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.addons - 4.1.16-SNAPSHOT WSO2 Carbon - Application Management Add-Ons WSO2 Carbon - Application Management Add-Ons https://entgra.io diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml index 591b2f46f1..6a84b225e1 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml @@ -22,13 +22,12 @@ application-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.api - 4.1.16-SNAPSHOT war WSO2 Carbon - Application Management API WSO2 Carbon - Application Management API diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml index e195e08097..9f50930c4f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml index 876c0ab594..9bc4a1dcf4 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml @@ -21,13 +21,12 @@ org.wso2.carbon.devicemgt application-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.common - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Application Management Common WSO2 Carbon - Application Management Common @@ -56,7 +55,7 @@ io.swagger.annotations.*;resolution:=optional, com.fasterxml.jackson.annotation, javax.validation.constraints, - javax.xml.bind.annotation.*, + javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", org.wso2.carbon.device.application.mgt.common.* diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceSubscriptionData.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceSubscriptionData.java index 3afac36acd..550c1c98fc 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceSubscriptionData.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/DeviceSubscriptionData.java @@ -24,7 +24,7 @@ import java.sql.Timestamp; public class DeviceSubscriptionData { private String action; - private Timestamp actionTriggeredTimestamp; + private long actionTriggeredTimestamp; private String actionTriggeredBy; private String actionType; private String status; @@ -38,11 +38,11 @@ public class DeviceSubscriptionData { this.action = action; } - public Timestamp getActionTriggeredTimestamp() { + public long getActionTriggeredTimestamp() { return actionTriggeredTimestamp; } - public void setActionTriggeredTimestamp(Timestamp actionTriggeredTimestamp) { + public void setActionTriggeredTimestamp(long actionTriggeredTimestamp) { this.actionTriggeredTimestamp = actionTriggeredTimestamp; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ScheduledSubscriptionDTO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ScheduledSubscriptionDTO.java index 65801e9415..da3e1e01e0 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ScheduledSubscriptionDTO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ScheduledSubscriptionDTO.java @@ -69,7 +69,7 @@ public class ScheduledSubscriptionDTO { /** * Scheduled time of subscription. */ - private LocalDateTime scheduledAt; + private long scheduledAt; /** * Username of the scheduler. @@ -86,7 +86,7 @@ public class ScheduledSubscriptionDTO { } - public ScheduledSubscriptionDTO(String taskName, String applicationUUID, LocalDateTime scheduledAt, + public ScheduledSubscriptionDTO(String taskName, String applicationUUID, long scheduledAt, List subscriberList, String scheduledBy) { this.taskName = taskName; this.applicationUUID = applicationUUID; @@ -135,11 +135,11 @@ public class ScheduledSubscriptionDTO { this.status = status; } - public LocalDateTime getScheduledAt() { + public long getScheduledAt() { return scheduledAt; } - public void setScheduledAt(LocalDateTime scheduledAt) { + public void setScheduledAt(long scheduledAt) { this.scheduledAt = scheduledAt; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java index 9d9e94c183..a535ffd389 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/SubscriptionManager.java @@ -22,6 +22,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.ScheduledSubscriptionDT import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.SubscriptionManagementException; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import java.util.List; @@ -127,14 +128,11 @@ public interface SubscriptionManager { * This method used to get the app id ,device ids and pass them to DM service method. * * @param appUUID UUID of the application release. - * @param offsetValue offset value for get paginated request. - * @param limitValue limit value for get paginated request. - * @param status status of the devices. + * @param request paginated request object. * @return deviceDetails - device details for given application release. * @throws {@link ApplicationManagementException} Exception of the application management */ - PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, - List status) throws ApplicationManagementException; + PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID) throws ApplicationManagementException; /*** * This method used to get category details. @@ -152,14 +150,15 @@ public interface SubscriptionManager { /** * This method is responsible to provide application subscription data for given application release UUID. * - * @param offsetValue offset - * @param limitValue limit + * @param request paginated request object. + * @param actionStatus status of the operation. + * @param action action related to the device. * @param appUUID application release UUID * @return {@link PaginationResult} * @throws ApplicationManagementException if offset or limit contains incorrect values, if it couldn't find an * application release for given UUID, if an error occurred while getting device details of subscribed device ids, * if an error occurred while getting subscription details of given application release UUID. */ - PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID) + PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action) throws ApplicationManagementException; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml index 82d75d4687..1bf38faaaa 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml @@ -21,13 +21,12 @@ org.wso2.carbon.devicemgt application-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.core - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Application Management Core WSO2 Carbon - Application Management Core @@ -51,8 +50,8 @@ Application Management Core Bundle org.wso2.carbon.device.application.mgt.core.internal - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context.*, @@ -62,8 +61,8 @@ javax.sql, com.google.gson.*, javax.naming, - javax.xml.bind.annotation, - javax.xml.bind, + javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", + javax.xml.bind; version="${javax.xml.bind.imp.pkg.version}", org.wso2.carbon.device.application.mgt.common.*, org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.device.mgt.common.*, @@ -87,8 +86,6 @@ org.apache.commons.validator.routines apk-parser;scope=compile|runtime;inline=false - - !org.wso2.carbon.device.application.mgt.core.internal.*, org.wso2.carbon.device.application.mgt.core.* @@ -348,6 +345,10 @@ + + org.wso2.carbon.devicemgt + org.wso2.carbon.identity.jwt.client.extension + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java index 4b99420e50..ce8780a6a2 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/SubscriptionDAO.java @@ -81,7 +81,7 @@ public interface SubscriptionDAO { void addGroupSubscriptions(int tenantId, String subscribedBy, List groups, int releaseId, String action) throws ApplicationManagementDAOException; - List getDeviceSubscriptions(int appReleaseId, int tenantId) throws + List getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws ApplicationManagementDAOException; Map getDeviceSubscriptions(List deviceIds, int appReleaseId, int tenantId) @@ -124,7 +124,7 @@ public interface SubscriptionDAO { * @param scheduledBy username of the user who scheduled the subscription * @throws ApplicationManagementDAOException if error occurred while updating the entry */ - boolean updateScheduledSubscription(int id, LocalDateTime scheduledAt, String scheduledBy) + boolean updateScheduledSubscription(int id, long scheduledAt, String scheduledBy) throws ApplicationManagementDAOException; /** diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index a4d9d4a87a..dd8880c6fc 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -134,7 +134,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " - + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " + "INNER JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " @@ -181,7 +182,17 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic if (filter.getLimit() != -1) { sql += "LIMIT ? OFFSET ? "; } - sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; + sql += ") AS app_data ON app_data.ID = AP_APP.ID " + + "INNER JOIN (" + + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " + + "FROM AP_APP_LIFECYCLE_STATE " + + "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE " + + "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "WHERE AP_APP.TENANT_ID = ? " + + "ORDER BY AP_APP.ID, LATEST_UPDATE DESC"; + try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java index c57ef8a07d..bb705d7f82 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java @@ -80,7 +80,8 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl { + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " - + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " + "INNER JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " @@ -125,7 +126,17 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl { if (filter.getLimit() != -1) { sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; } - sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; + sql += ") AS app_data ON app_data.ID = AP_APP.ID " + + "INNER JOIN (" + + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " + + "FROM AP_APP_LIFECYCLE_STATE " + + "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE " + + "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "WHERE AP_APP.TENANT_ID = ? " + + "ORDER BY AP_APP.ID, LATEST_UPDATE DESC"; + try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java index ee7c78f8ba..d27e55aa9b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java @@ -79,7 +79,8 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " - + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " + "INNER JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " @@ -124,7 +125,17 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { if (filter.getLimit() != -1) { sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; } - sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; + sql += ") AS app_data ON app_data.ID = AP_APP.ID " + + "INNER JOIN (" + + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " + + "FROM AP_APP_LIFECYCLE_STATE " + + "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE " + + "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + + "WHERE AP_APP.TENANT_ID = ? " + + "ORDER BY AP_APP.ID, LATEST_UPDATE DESC"; + try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java index c2f559e96b..c2fd7f240a 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/subscription/GenericSubscriptionDAOImpl.java @@ -332,12 +332,15 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } @Override - public List getDeviceSubscriptions(int appReleaseId, int tenantId) throws + public List getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting device subscriptions for the application release id " + appReleaseId + " from the database"); } + boolean isActionStatusProvided = false; + boolean isActionProvided = false; + int index = 1; String sql = "SELECT " + "DS.ID AS ID, " + "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, " @@ -350,11 +353,30 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc + "DS.DM_DEVICE_ID AS DEVICE_ID " + "FROM AP_DEVICE_SUBSCRIPTION DS " + "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.TENANT_ID=?"; + + if (actionStatus != null && !actionStatus.isEmpty()) { + sql += " AND DS.STATUS= ?"; + isActionStatusProvided = true; + } + if (action != null && !action.isEmpty()) { + sql += " AND DS.UNSUBSCRIBED= ?"; + isActionProvided = true; + } try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, appReleaseId); - stmt.setInt(2, tenantId); + stmt.setInt(index++, appReleaseId); + stmt.setInt(index++, tenantId); + if (isActionStatusProvided) { + stmt.setString(index++, actionStatus); + } + if (isActionProvided) { + if (action.equals("SUBSCRIBED")) { + stmt.setString(index, "FALSE"); + } else { + stmt.setString(index, "TRUE"); + } + } try (ResultSet rs = stmt.executeQuery()) { if (log.isDebugEnabled()) { log.debug("Successfully retrieved device subscriptions for application release id " @@ -765,7 +787,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc stmt.setString(2, subscriptionDTO.getApplicationUUID()); stmt.setString(3, subscriptionDTO.getSubscribersString()); stmt.setString(4, ExecutionStatus.PENDING.toString()); - stmt.setTimestamp(5, Timestamp.valueOf(subscriptionDTO.getScheduledAt())); + stmt.setLong(5, subscriptionDTO.getScheduledAt()); stmt.setTimestamp(6, new Timestamp(calendar.getTime().getTime())); stmt.setString(7, subscriptionDTO.getScheduledBy()); stmt.setBoolean(8, false); @@ -785,7 +807,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc } @Override - public boolean updateScheduledSubscription(int id, LocalDateTime scheduledAt, String scheduledBy) + public boolean updateScheduledSubscription(int id, long scheduledAt, String scheduledBy) throws ApplicationManagementDAOException { String sql = "UPDATE AP_SCHEDULED_SUBSCRIPTION " + "SET " @@ -797,7 +819,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { Calendar calendar = Calendar.getInstance(); - stmt.setTimestamp(1, Timestamp.valueOf(scheduledAt)); + stmt.setLong(1, scheduledAt); stmt.setString(2, scheduledBy); stmt.setTimestamp(3, new Timestamp(calendar.getTime().getTime())); stmt.setInt(4, id); @@ -1037,7 +1059,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, ExecutionStatus.PENDING.toString()); stmt.setBoolean(2, false); - stmt.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime())); + stmt.setLong(3, Calendar.getInstance().getTime().getTime() / 1000); try (ResultSet rs = stmt.executeQuery()) { return DAOUtil.loadScheduledSubscriptions(rs); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index 2cebd98c61..05b757ba45 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -1445,7 +1445,7 @@ ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new ForbiddenException(msg); } - if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId).isEmpty()) { + if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null).isEmpty()) { String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() + " either subscribed to device/s or it had subscribed to device/s. Therefore you are not " + "permitted to delete the application release."; @@ -1580,7 +1580,7 @@ ApplicationManagerImpl implements ApplicationManager { try { ConnectionManagerUtil.beginDBTransaction(); List deviceSubscriptionDTOS = subscriptionDAO - .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId); + .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null); if (!deviceSubscriptionDTOS.isEmpty()) { String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() + " either subscribed to device/s or it had subscribed to device/s. Therefore you " diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index 19008cbb0d..5aa222ce13 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -65,10 +65,7 @@ import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.Constants; import org.wso2.carbon.device.application.mgt.core.util.HelperUtil; import org.wso2.carbon.device.application.mgt.core.util.OAuthUtils; -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.MDMAppConstants; +import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.app.mgt.App; import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes; import org.wso2.carbon.device.mgt.common.app.mgt.android.CustomApplication; @@ -88,7 +85,6 @@ import org.wso2.carbon.device.mgt.core.util.MDMIOSOperationUtil; import org.wso2.carbon.device.mgt.core.util.MDMWindowsOperationUtil; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.device.mgt.common.PaginationResult; import javax.ws.rs.core.MediaType; import java.io.BufferedReader; @@ -381,7 +377,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (applicationDTO != null) { List deviceSubscriptionDTOS = this.subscriptionDAO .getDeviceSubscriptions(applicationDTO.getApplicationReleaseDTOs().get(0).getId(), - tenantId); + tenantId, null, null); AtomicBoolean isAppSubscribable = new AtomicBoolean(true); for (DeviceSubscriptionDTO deviceSubscriptionDTO : deviceSubscriptionDTOS) { @@ -1223,7 +1219,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } @Override - public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, List status) + public PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); DeviceManagementProviderService deviceManagementProviderService = HelperUtil @@ -1235,7 +1231,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId(); List deviceSubscriptionDTOS = subscriptionDAO - .getDeviceSubscriptions(applicationReleaseId, tenantId); + .getDeviceSubscriptions(applicationReleaseId, tenantId, null, null); if (deviceSubscriptionDTOS.isEmpty()) { PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(new ArrayList<>()); @@ -1262,8 +1258,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } //pass the device id list to device manager service method try { - PaginationResult deviceDetails = deviceManagementProviderService - .getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, status); + PaginationResult deviceDetails = deviceManagementProviderService.getAppSubscribedDevices + (request, deviceIdList); if (deviceDetails == null) { String msg = "Couldn't found an subscribed devices details for device ids: " + deviceIdList; @@ -1342,8 +1338,10 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } @Override - public PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID) - throws ApplicationManagementException { + public PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, + String action) throws ApplicationManagementException { + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); DeviceManagementProviderService deviceManagementProviderService = HelperUtil .getDeviceManagementProviderService(); @@ -1365,7 +1363,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId(); List deviceSubscriptionDTOS = subscriptionDAO - .getDeviceSubscriptions(applicationReleaseId, tenantId); + .getDeviceSubscriptions(applicationReleaseId, tenantId, actionStatus, action); if (deviceSubscriptionDTOS.isEmpty()) { PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(new ArrayList<>()); @@ -1377,8 +1375,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { .collect(Collectors.toList()); try { //pass the device id list to device manager service method - PaginationResult paginationResult = deviceManagementProviderService - .getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, null); + PaginationResult paginationResult = deviceManagementProviderService.getAppSubscribedDevices + (request, deviceIdList); List deviceSubscriptionDataList = new ArrayList<>(); if (!paginationResult.getData().isEmpty()) { @@ -1392,12 +1390,12 @@ public class SubscriptionManagerImpl implements SubscriptionManager { deviceSubscriptionData.setAction(Constants.UNSUBSCRIBED); deviceSubscriptionData.setActionTriggeredBy(subscription.getUnsubscribedBy()); deviceSubscriptionData - .setActionTriggeredTimestamp(subscription.getUnsubscribedTimestamp()); + .setActionTriggeredTimestamp(subscription.getUnsubscribedTimestamp().getTime() / 1000); } else { deviceSubscriptionData.setAction(Constants.SUBSCRIBED); deviceSubscriptionData.setActionTriggeredBy(subscription.getSubscribedBy()); deviceSubscriptionData - .setActionTriggeredTimestamp(subscription.getSubscribedTimestamp()); + .setActionTriggeredTimestamp(subscription.getSubscribedTimestamp().getTime() / 1000); } deviceSubscriptionData.setActionType(subscription.getActionTriggeredFrom()); deviceSubscriptionData.setStatus(subscription.getStatus()); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java index 113b16cf3f..351a4477b2 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java @@ -40,7 +40,7 @@ public class ScheduledAppSubscriptionCleanupTask extends RandomlyAssignedSchedul @Override public void executeRandomlyAssignedTask() { try { - if(super.isQualifiedToExecuteTask()) { + if(isQualifiedToExecuteTask()) { subscriptionManager.cleanScheduledSubscriptions(); } } catch (SubscriptionManagementException e) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java index caff4ec460..8a95efc0aa 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java @@ -68,7 +68,7 @@ public class ScheduledAppSubscriptionTask extends RandomlyAssignedScheduleTask { @Override public void executeRandomlyAssignedTask() { - if(super.isQualifiedToExecuteTask()) { + if(isQualifiedToExecuteTask()) { try { ScheduledSubscriptionDTO subscriptionDTO = subscriptionManager.getPendingScheduledSubscription( this.taskName); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java index c07053f3d5..326a358e1b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTaskManager.java @@ -40,6 +40,8 @@ import org.wso2.carbon.ntask.core.service.TaskService; import java.time.LocalDateTime; import java.time.format.TextStyle; +import java.util.Calendar; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -64,24 +66,27 @@ public class ScheduledAppSubscriptionTaskManager { * either {@link org.wso2.carbon.device.mgt.common.DeviceIdentifier} if {@param subType} is * equal to DEVICE or {@link String} if {@param subType} is USER, ROLE or GROUP * @param subscriptionType subscription type. E.g. DEVICE, USER, ROLE, GROUP - * {@see {@link org.wso2.carbon.device.application.mgt.common.SubscriptionType}} + * {@see {@link SubscriptionType}} * @param action action subscription action. E.g. {@code INSTALL/UNINSTALL} - * {@see {@link org.wso2.carbon.device.application.mgt.common.SubAction}} + * {@see {@link SubAction}} * @param timestamp timestamp to schedule the application subscription * @throws ApplicationOperationTaskException if error occurred while scheduling the subscription */ public void scheduleAppSubscriptionTask(String applicationUUID, List subscribers, - SubscriptionType subscriptionType, SubAction action, LocalDateTime timestamp) + SubscriptionType subscriptionType, SubAction action, long timestamp) throws ApplicationOperationTaskException { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date(timestamp * 1000)); String space = " "; String cronExpression = - String.valueOf(timestamp.getSecond()) + space + timestamp.getMinute() + space + timestamp.getHour() - + space + timestamp.getDayOfMonth() + space + timestamp.getMonth().getDisplayName(TextStyle.SHORT, - Locale.getDefault()).toUpperCase() + " ? " + timestamp.getYear(); + calendar.get(Calendar.SECOND) + space + calendar.get(Calendar.MINUTE) + space + + calendar.get(Calendar.HOUR_OF_DAY) + space + calendar.get(Calendar.DAY_OF_MONTH) + space + + calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()).toUpperCase() + " ? " + + calendar.get(Calendar.YEAR); if (!CronExpression.isValidExpression(cronExpression)) { String msg = "The cron expression [" + cronExpression + "] generated by the" + " timestamp [" + timestamp - .toString() + "] is invalid"; + + "] is invalid"; log.error(msg); throw new ApplicationOperationTaskException(msg); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java index c56df53109..4950fe3c6e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java @@ -274,7 +274,7 @@ public class DAOUtil { } subscription.setStatus(ExecutionStatus.valueOf(rs.getString("STATUS"))); - subscription.setScheduledAt(rs.getTimestamp("SCHEDULED_AT").toLocalDateTime()); + subscription.setScheduledAt(rs.getLong("SCHEDULED_AT")); subscription.setScheduledBy(rs.getString("SCHEDULED_BY")); subscription.setDeleted(rs.getBoolean("DELETED")); subscriptionDTOS.add(subscription); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/OAuthUtils.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/OAuthUtils.java index b57ffebeb7..33a9d0706f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/OAuthUtils.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/OAuthUtils.java @@ -63,7 +63,7 @@ public class OAuthUtils { apiApplicationKeyInfo = apiManagementProviderService. generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), registrationProfile.getTags(), Constants.ApplicationInstall.DEFAULT_TOKEN_TYPE, - registrationProfile.getApplicationName(), registrationProfile.isAllowedToAllDomains(), + null, registrationProfile.isAllowedToAllDomains(), Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD); } finally { PrivilegedCarbonContext.endTenantFlow(); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml index cc88e04256..75586560be 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml @@ -22,13 +22,12 @@ application-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.publisher.api - 4.1.16-SNAPSHOT war WSO2 Carbon - Application Management Publisher API WSO2 Carbon - Application Management Publisher API diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/META-INF/webapp-classloading.xml index da8baef61f..7a71395445 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/pom.xml index c23da83cb2..480264b88a 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/pom.xml @@ -22,13 +22,12 @@ application-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.store.api - 4.1.16-SNAPSHOT war WSO2 Carbon - Application Management Store API WSO2 Carbon - Application Management Store API diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java index 75a4522d68..be55b64639 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/SubscriptionManagementAPI.java @@ -32,6 +32,7 @@ import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import javax.validation.Valid; +import javax.validation.constraints.Size; import javax.ws.rs.Path; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; @@ -129,7 +130,7 @@ public interface SubscriptionManagementAPI { name = "timestamp", value = "Timestamp of scheduled install/uninstall operation" ) - @QueryParam("timestamp") String timestamp + @QueryParam("timestamp") long timestamp ); @POST @@ -182,7 +183,7 @@ public interface SubscriptionManagementAPI { name = "timestamp", value = "Timestamp of scheduled install/uninstall operation" ) - @QueryParam("timestamp") String timestamp + @QueryParam("timestamp") long timestamp ); @POST @@ -229,7 +230,7 @@ public interface SubscriptionManagementAPI { name = "timestamp", value = "Timestamp of scheduled ent. install operation" ) - @QueryParam("timestamp") String timestamp, + @QueryParam("timestamp") long timestamp, @ApiParam( name = "requiresUpdatingExternal", value = "Should external system such as Google EMM APIs need to be updated." @@ -287,7 +288,7 @@ public interface SubscriptionManagementAPI { name = "timestamp", value = "Timestamp of scheduled ent app install operation" ) - @QueryParam("timestamp") String timestamp, + @QueryParam("timestamp") long timestamp, @ApiParam( name = "requiresUpdatingExternal", value = "Should external system such as Google EMM APIs need to be updated." @@ -337,6 +338,28 @@ public interface SubscriptionManagementAPI { response = ErrorResponse.class) }) Response getAppInstalledDevices( + @ApiParam( + name = "name", + value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.", + required = false) + @Size(max = 45) + String name, + @ApiParam( + name = "user", + value = "The username of the owner of the device.", + required = false) + @QueryParam("user") + String user, + @ApiParam( + name = "ownership", + allowableValues = "BYOD, COPE", + value = "Provide the ownership status of the device. The following values can be assigned:\n" + + "- BYOD: Bring Your Own Device\n" + + "- COPE: Corporate-Owned, Personally-Enabled", + required = false) + @QueryParam("ownership") + @Size(max = 45) + String ownership, @ApiParam( name="uuid", value="uuid of the application release.", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/admin/SubscriptionManagementAdminAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/admin/SubscriptionManagementAdminAPI.java index 7c47b1f7cf..97f6f6851e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/admin/SubscriptionManagementAdminAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/admin/SubscriptionManagementAdminAPI.java @@ -31,6 +31,7 @@ import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.application.mgt.common.ErrorResponse; +import javax.validation.constraints.Size; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -111,6 +112,32 @@ public interface SubscriptionManagementAdminAPI { response = ErrorResponse.class) }) Response getAppInstalledDevices( + @ApiParam( + name = "name", + value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.", + required = false) + @Size(max = 45) + String name, + @ApiParam( + name = "user", + value = "The username of the owner of the device.", + required = false) + @QueryParam("user") + String user, + @ApiParam( + name = "action", + value = "The action, subscribed or unsubscribed.", + required = false) + @Size(max = 45) + @QueryParam("action") String action, + @ApiParam( + name = "actionStatus", + value = "Provide the action status details") + @QueryParam("actionStatus") String actionStatus, + @ApiParam( + name = "status", + value = "Provide the device status details, such as active or inactive.") + @QueryParam("status") List status, @ApiParam( name = "uuid", value = "uuid of the application release.", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java index 984f689d07..acf9662cb9 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java @@ -33,6 +33,8 @@ import org.wso2.carbon.device.application.mgt.common.BasicUserInfo; import org.wso2.carbon.device.application.mgt.common.BasicUserInfoList; import org.wso2.carbon.device.application.mgt.common.RoleList; import org.wso2.carbon.device.application.mgt.common.DeviceGroupList; +import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; @@ -73,9 +75,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @PathParam("uuid") String uuid, @PathParam("action") String action, @Valid List deviceIdentifiers, - @QueryParam("timestamp") String timestamp) { + @QueryParam("timestamp") long timestamp) { try { - if (StringUtils.isEmpty(timestamp)) { + if (0 == timestamp) { SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); ApplicationInstallResponse response = subscriptionManager .performBulkAppOperation(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(), action); @@ -114,9 +116,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @PathParam("subType") String subType, @PathParam("action") String action, @Valid List subscribers, - @QueryParam("timestamp") String timestamp) { + @QueryParam("timestamp") long timestamp) { try { - if (StringUtils.isEmpty(timestamp)) { + if (0 == timestamp) { SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); ApplicationInstallResponse response = subscriptionManager .performBulkAppOperation(uuid, subscribers, subType, action); @@ -155,10 +157,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @PathParam("uuid") String uuid, @PathParam("action") String action, @Valid List deviceIdentifiers, - @QueryParam("timestamp") String timestamp, + @QueryParam("timestamp") long timestamp, @QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) { try { - if (StringUtils.isEmpty(timestamp)) { + if (0 == timestamp) { SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); subscriptionManager .performEntAppSubscription(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(), @@ -202,10 +204,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @PathParam("subType") String subType, @PathParam("action") String action, @Valid List subscribers, - @QueryParam("timestamp") String timestamp, + @QueryParam("timestamp") long timestamp, @QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) { try { - if (StringUtils.isEmpty(timestamp)) { + if (0 == timestamp) { SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); subscriptionManager.performEntAppSubscription(uuid, subscribers, subType, action, requiresUpdatingExternal); String msg = "Application release which has UUID " + uuid + " is installed to subscriber's valid device" @@ -253,11 +255,11 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ * @return {@link Response} of the operation */ private Response scheduleApplicationOperationTask(String applicationUUID, List subscribers, - SubscriptionType subType, SubAction subAction, String timestamp) { + SubscriptionType subType, SubAction subAction, long timestamp) { try { ScheduledAppSubscriptionTaskManager subscriptionTaskManager = new ScheduledAppSubscriptionTaskManager(); subscriptionTaskManager.scheduleAppSubscriptionTask(applicationUUID, subscribers, subType, subAction, - LocalDateTime.parse(timestamp, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); + timestamp); } catch (ApplicationOperationTaskException e) { String msg = "Error occurred while scheduling the application install operation"; log.error(msg, e); @@ -273,6 +275,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @Produces("application/json") @Path("/{uuid}/devices") public Response getAppInstalledDevices( + @QueryParam("name") String name, + @QueryParam("user") String user, + @QueryParam("ownership") String ownership, @PathParam("uuid") String uuid, @DefaultValue("0") @QueryParam("offset") int offset, @@ -281,8 +286,31 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ @QueryParam("status") List status) { try { SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); - PaginationResult subscribedDeviceDetails = subscriptionManager - .getAppInstalledDevices(offset, limit, uuid, status); + PaginationRequest request = new PaginationRequest(offset, limit); + if (name != null && !name.isEmpty()) { + request.setDeviceName(name); + } + if (user != null && !user.isEmpty()) { + request.setOwner(user); + } + if (ownership != null && !ownership.isEmpty()) { + RequestValidationUtil.validateOwnershipType(ownership); + request.setOwnership(ownership); + } + if (status != null && !status.isEmpty()) { + boolean isStatusEmpty = true; + for (String statusString : status) { + if (StringUtils.isNotBlank(statusString)) { + isStatusEmpty = false; + break; + } + } + if (!isStatusEmpty) { + RequestValidationUtil.validateStatus(status); + request.setStatusList(status); + } + } + PaginationResult subscribedDeviceDetails = subscriptionManager.getAppInstalledDevices(request, uuid); DeviceList devices = new DeviceList(); devices.setList((List) subscribedDeviceDetails.getData()); devices.setCount(subscribedDeviceDetails.getRecordsTotal()); @@ -292,8 +320,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{ log.error(msg, e); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } catch (BadRequestException e) { - String msg = "Found invalid payload for getting application which has UUID: " + uuid - + ". Hence verify the payload"; + String msg = "User requested details are not valid"; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ForbiddenException e) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java index 2462556570..681b3b5f38 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.application.mgt.store.api.services.impl.admin; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; @@ -26,6 +27,8 @@ import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.store.api.services.admin.SubscriptionManagementAdminAPI; +import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import javax.ws.rs.Consumes; @@ -36,6 +39,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; +import java.util.List; /** * Implementation of Subscription Management related APIs. @@ -51,6 +55,11 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen @Produces("application/json") @Path("/{uuid}") public Response getAppInstalledDevices( + @QueryParam("name") String name, + @QueryParam("user") String user, + @QueryParam("action") String action, + @QueryParam("actionStatus") String actionStatus, + @QueryParam("status") List status, @PathParam("uuid") String uuid, @DefaultValue("0") @QueryParam("offset") int offset, @@ -58,22 +67,49 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen @QueryParam("limit") int limit) { try { + PaginationRequest request = new PaginationRequest(offset, limit); + if (name != null && !name.isEmpty()) { + request.setDeviceName(name); + } + if (user != null && !user.isEmpty()) { + request.setOwner(user); + } + if (action != null && !action.isEmpty()) { + RequestValidationUtil.validateAction(action); + } + if (status != null && !status.isEmpty()) { + boolean isStatusEmpty = true; + for (String statusString : status) { + if (StringUtils.isNotBlank(statusString)) { + isStatusEmpty = false; + break; + } + } + if (!isStatusEmpty) { + RequestValidationUtil.validateStatus(status); + request.setStatusList(status); + } + } + if (actionStatus != null && !actionStatus.isEmpty()) { + if (StringUtils.isNotBlank(actionStatus)) { + RequestValidationUtil.validateStatusFiltering(actionStatus); + } + } SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); - PaginationResult subscriptionData = subscriptionManager - .getAppSubscriptionDetails(offset, limit, uuid); + PaginationResult subscriptionData = subscriptionManager.getAppSubscriptionDetails + (request, uuid, actionStatus, action); return Response.status(Response.Status.OK).entity(subscriptionData).build(); } catch (NotFoundException e) { String msg = "Application with application release UUID: " + uuid + " is not found"; log.error(msg, e); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } catch (BadRequestException e) { - String msg = "Found invalid payload for getting application which has UUID: " + uuid - + ". Hence verify the payload"; + String msg = "User requested details are not valid"; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while getting app installed devices which has application release UUID of: " - + uuid; + + uuid; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/util/RequestValidationUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/util/RequestValidationUtil.java new file mode 100644 index 0000000000..2a59d220a4 --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/services/impl/util/RequestValidationUtil.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2021, 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.application.mgt.store.api.services.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException; +import org.wso2.carbon.device.application.mgt.store.api.util.Constants; + +import java.util.List; + +public class RequestValidationUtil { + + private static final Log log = LogFactory.getLog(RequestValidationUtil.class); + + /** + * Checks if user requested status codes are valid. + * + * @param statusList status codes upon to filter operation logs using status + */ + public static void validateStatus(List statusList) throws BadRequestException { + for (String status : statusList) { + switch (status) { + case "ACTIVE": + case "INACTIVE": + case "UNCLAIMED": + case "UNREACHABLE": + case "SUSPENDED": + case "DISENROLLMENT_REQUESTED": + case "REMOVED": + case "BLOCKED": + case "CREATED": + break; + default: + String msg = "Invalid enrollment status type: " + status + ". \nValid status types " + + "are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE | SUSPENDED | " + + "DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; + log.error(msg); + throw new BadRequestException(msg); + } + } + } + + /** + * Checks if user requested action is valid. + * + * @param action action upon to filter devices using action + */ + public static void validateAction(String action) throws BadRequestException { + if (action.equals("SUBSCRIBED") || action.equals("UNSUBSCRIBED")) { + } else { + String msg = "Invalid action type received.Valid action types are SUBSCRIBED | UNSUBSCRIBED"; + log.error(msg); + throw new BadRequestException(msg); + } + } + + /** + * Checks if user requested ownerships are valid. + * + * @param ownership ownerships upon to filter devices using ownership + */ + public static void validateOwnershipType(String ownership) throws BadRequestException { + switch (ownership) { + case "BYOD": + case "COPE": + case "WORK_PROFILE": + case "GOOGLE_ENTERPRISE": + case "COSU": + case "FULLY_MANAGED": + case "DEDICATED_DEVICE": + break; + default: + String msg = "Invalid ownership type received.Valid ownership types are BYOD | COPE | WORK_PROFILE |" + + "GOOGLE_ENTERPRISE | COSU | FULLY_MANAGED | DEDICATED_DEVICE"; + log.error(msg); + throw new BadRequestException(msg); + } + } + + /** + * Checks if user requested Action status codes are valid. + * + * @param status status codes upon to filter operation logs using status + */ + public static void validateStatusFiltering(String status) throws BadRequestException { + if (Constants.OperationStatus.COMPLETED.toUpperCase().equals(status) + || Constants.OperationStatus.ERROR.toUpperCase().equals(status) + || Constants.OperationStatus.NOTNOW.toUpperCase().equals(status) + || Constants.OperationStatus.REPEATED.toUpperCase().equals(status) + || Constants.OperationStatus.PENDING.toUpperCase().equals(status) + || Constants.OperationStatus.IN_PROGRESS.toUpperCase().equals(status)) { + } else { + String msg = "Invalid status type: " + status + ". \nValid status types are COMPLETED | ERROR | " + + "IN_PROGRESS | NOTNOW | PENDING | REPEATED"; + log.error(msg); + throw new BadRequestException(msg); + } + } +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/util/Constants.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/util/Constants.java new file mode 100644 index 0000000000..a78c16077f --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/java/org/wso2/carbon/device/application/mgt/store/api/util/Constants.java @@ -0,0 +1,101 @@ +/* + * 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. + * + * + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. 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.application.mgt.store.api.util; + +/** + * Holds the constants used by DeviceImpl Management Admin web application. + */ +public class Constants { + + public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress"; + public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname"; + public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname"; + public static final String USER_CLAIM_CREATED = "http://wso2.org/claims/created"; + public static final String USER_CLAIM_MODIFIED = "http://wso2.org/claims/modified"; + public static final String USER_CLAIM_DEVICES = "http://wso2.org/claims/devices"; + public static final String PRIMARY_USER_STORE = "PRIMARY"; + public static final String DEFAULT_STREAM_VERSION = "1.0.0"; + public static final String SCOPE = "scope"; + public static final String JDBC_USERSTOREMANAGER = "org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager"; + public static final String DEFAULT_SIMPLE_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; + public static final int DEFAULT_PAGE_LIMIT = 50; + public static final String FORWARD_SLASH = "/"; + public static final String ANDROID = "android"; + public static final String ANDROID_POLICY_VALIDATOR = "io.entgra.proprietary.platform.android." + + "core.polcy.AndroidPolicyPayloadValidator"; + public static final String IOS = "ios"; + public static final String WINDOWS = "windows"; + + + public final class OperationStatus { + private OperationStatus () { throw new AssertionError(); } + public static final String COMPLETED = "completed"; + public static final String ERROR = "error"; + public static final String IN_PROGRESS = "in_progress"; + public static final String PENDING = "pending"; + public static final String NOTNOW = "notnow"; + public static final String REPEATED = "repeated"; + } + public static final String DEVICES = "devices"; + public static final String ATTRIBUTE_DISPLAY_NAME = "DisplayName"; + public static final String ATTRIBUTE_DESCRIPTION = "Description"; + public static final String EXTERNAL_DEVICE_CLAIM_DISPLAY_NAME = "Devices"; + public static final String EXTERNAL_DEVICE_CLAIM_DESCRIPTION = "Device list"; + + public final class ErrorMessages { + private ErrorMessages () { throw new AssertionError(); } + + public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request"; + + } + + public final class DeviceConstants { + private DeviceConstants () { throw new AssertionError(); } + + public static final String APPLICATION_JSON = "application/json"; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + } + + public final class Permission { + private Permission() { throw new AssertionError(); } + + public static final String ADMIN = "/permission/admin"; + public static final String LOGIN = "/permission/admin/login"; + public static final String DEVICE_MGT = "/permission/admin/device-mgt"; + public static final String APP_MGT = "/permission/admin/app-mgt"; + } + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/webapp/META-INF/webapp-classloading.xml index da8baef61f..7a71395445 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.store.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 8d20275116..53a4256688 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,13 +22,12 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 application-mgt - 4.1.16-SNAPSHOT pom WSO2 Carbon - Application Management Component WSO2 Carbon - Application Management Component diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml index fa191390be..2e4defe98c 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -134,9 +134,16 @@ - org.apache.cxf - cxf-rt-frontend-jaxws + org.springframework + spring-web + provided + + org.apache.cxf + cxf-bundle-jaxrs + provided + + commons-codec.wso2 commons-codec @@ -147,24 +154,11 @@ - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.apache.cxf - cxf-rt-transports-http - junit junit test - - javax.ws.rs - jsr311-api - provided - org.wso2.carbon org.wso2.carbon.logging @@ -207,11 +201,6 @@ - - javax.servlet - javax.servlet-api - provided - org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml index ed2ed21624..60db8782e9 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index cbe533dd6d..d5e645e24f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -133,9 +133,15 @@ + + org.springframework + spring-web + provided + org.apache.cxf - cxf-rt-frontend-jaxws + cxf-bundle-jaxrs + provided commons-codec.wso2 @@ -147,14 +153,6 @@ - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.apache.cxf - cxf-rt-transports-http - junit junit @@ -204,11 +202,6 @@ - - javax.servlet - javax.servlet-api - provided - org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml index ed2ed21624..60db8782e9 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index 6942c86d84..b129c7affa 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -38,13 +38,12 @@ org.wso2.carbon.devicemgt certificate-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.core - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Certificate Management Core WSO2 Carbon - Certificate Management Core @@ -72,8 +71,8 @@ org.wso2.carbon.certificate.mgt.core.util - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, org.apache.commons.collections.map, javax.security.auth.x500, diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index df7948b53f..ebb7bae8ba 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt - 4.1.16-SNAPSHOT pom WSO2 Carbon - Certificate Management Component http://wso2.org diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml index 6c47262ab0..6116d38fc5 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -140,8 +140,8 @@ org.apache.axis2.deployment.*, org.apache.commons.lang;version="${commons-lang.wso2.osgi.version.range}", org.apache.commons.logging, - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.w3c.dom, org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.*, diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml index 14a9d8c308..ae6ddc3665 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -82,8 +82,8 @@ org.wso2.carbon.device.mgt.extensions.pull.notification.* - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.core.service diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml index b102c68e13..821389cf34 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -135,7 +135,8 @@ com.google.gson, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.push.notification, org.apache.commons.logging, diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml index 447951938b..4490ef70fa 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -126,13 +126,13 @@ org.apache.commons.logging, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.push.notification, org.wso2.carbon.device.mgt.common, org.wso2.carbon.device.mgt.core.service, - org.osgi.framework, org.wso2.carbon.device.mgt.core.operation.mgt, org.wso2.carbon.core, com.google.gson, diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index a59a3728a5..61f896e377 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -148,7 +148,8 @@ org.apache.commons.logging, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.push.notification, @@ -157,7 +158,6 @@ org.wso2.carbon.device.mgt.core.service, org.wso2.carbon.event.output.adapter.core, org.wso2.carbon.event.output.adapter.core.exception, - org.osgi.framework, org.wso2.carbon.device.mgt.core.operation.mgt, org.wso2.carbon.core, org.wso2.carbon.device.application.mgt.common.*, diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index 1a6e1a58ab..9150709a6b 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -135,14 +135,14 @@ org.apache.commons.logging, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.context, org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.push.notification, - org.wso2.carbon.device.mgt.core.service, + org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.event.output.adapter.core, org.wso2.carbon.event.output.adapter.core.exception, - org.osgi.framework, org.wso2.carbon.core, org.wso2.carbon.device.mgt.common.* diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index d55cf9ea49..f76390dbee 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml index bd43c8b626..85c915cd66 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -146,13 +146,13 @@ - org.apache.cxf - cxf-rt-frontend-jaxrs + org.springframework + spring-web provided org.apache.cxf - cxf-rt-transports-http + cxf-bundle-jaxrs provided diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/webapp/META-INF/webapp-classloading.xml index 01aceabde5..a16c0a9cbf 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml index 7e7060e5b2..2606d543c8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -107,8 +107,8 @@ org.wso2.carbon.device.mgt.analytics.data.publisher.*;version="${carbon.device.mgt.version}" - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging.*, org.wso2.carbon.utils.multitenancy, org.wso2.carbon.context;version="${carbon.kernel.version.range}", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml index bf9eedf2a7..4c495596d5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.wsproxy/pom.xml @@ -20,7 +20,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT 4.0.0 diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index d2992949d2..bae7d9e84a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -146,18 +146,13 @@ - org.apache.cxf - cxf-rt-frontend-jaxws + org.springframework + spring-web provided org.apache.cxf - cxf-rt-frontend-jaxrs - provided - - - org.apache.cxf - cxf-rt-transports-http + cxf-bundle-jaxrs provided @@ -165,11 +160,6 @@ commons-httpclient provided - - javax.ws.rs - jsr311-api - provided - org.wso2.carbon org.wso2.carbon.utils @@ -200,11 +190,6 @@ org.wso2.carbon.device.mgt.common provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - provided - org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.extensions @@ -340,6 +325,12 @@ javax.ws.rs javax.ws.rs-api + provided + + + javax.ws.rs + jsr311-api + provided org.wso2.carbon.commons @@ -350,11 +341,6 @@ org.wso2.carbon.analytics org.wso2.carbon.analytics.api provided - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.datasource.commons - provided org.wso2.carbon.devicemgt @@ -402,11 +388,6 @@ org.wso2.carbon.event.stream.persistence.stub provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.client - provided - org.powermock powermock-module-testng diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeoCluster.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeoCluster.java new file mode 100644 index 0000000000..4316e35b51 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeoCluster.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; + +public class GeoCluster { + private final GeoCoordinate coordinates; + private final GeoCoordinate southWestBound; + private final GeoCoordinate northEastBound; + private final long count; + private final String geohashPrefix; + private final String deviceIdentification; + private final String deviceName; + private final String deviceType; + private final String lastSeen; + + public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound, + long count, String geohashPrefix, String deviceIdentification, String deviceName, + String deviceType, String lastSeen) { + this.coordinates = coordinates; + this.southWestBound = southWestBound; + this.northEastBound = northEastBound; + this.count = count; + this.geohashPrefix = geohashPrefix; + this.deviceIdentification = deviceIdentification; + this.deviceName = deviceName; + this.deviceType = deviceType; + this.lastSeen = lastSeen; + } + + public String getGeohashPrefix() { + return geohashPrefix; + } + + public long getCount() { + return count; + } + + public GeoCoordinate getCoordinates() { + return coordinates; + } + + public GeoCoordinate getSouthWestBound() { + return southWestBound; + } + + public GeoCoordinate getNorthEastBound() { + return northEastBound; + } + + public String getDeviceIdentification() { + return deviceIdentification; + } + + public String getDeviceName() { + return deviceName; + } + + public String getDeviceType() { + return deviceType; + } + + public String getLastSeen() { + return lastSeen; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java index 9eddd91aeb..205f1b8ee2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java @@ -67,64 +67,65 @@ import javax.ws.rs.core.Response; @Consumes(MediaType.APPLICATION_JSON) public interface DeviceEventManagementService { - @POST - @Path("/{type}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Adding the Event Type Definition", - notes = "Add the event definition for a device.", - tags = "Device Event Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully added the event defintion.", - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = - "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - } - ), - @ApiResponse( - code = 400, - message = - "Bad Request. \n"), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the " + - "list of supported device types.", - response = ErrorResponse.class) - } - ) - Response deployDeviceTypeEventDefinition( - @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") - @PathParam("type")String deviceType, - @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") - @QueryParam("skipPersist") boolean skipPersist, - @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") - @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, - @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", - required = true) - @Valid DeviceTypeEvent deviceTypeEvent); + //todo:amalka +// @POST +// @Path("/{type}") +// @ApiOperation( +// produces = MediaType.APPLICATION_JSON, +// httpMethod = "POST", +// value = "Adding the Event Type Definition", +// notes = "Add the event definition for a device.", +// tags = "Device Event Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") +// }) +// } +// ) +// @ApiResponses( +// value = { +// @ApiResponse( +// code = 200, +// message = "OK. \n Successfully added the event defintion.", +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "ETag", +// description = "Entity Tag of the response resource.\n" + +// "Used by caches, or in conditional requests."), +// @ResponseHeader( +// name = "Last-Modified", +// description = +// "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests."), +// } +// ), +// @ApiResponse( +// code = 400, +// message = +// "Bad Request. \n"), +// @ApiResponse( +// code = 406, +// message = "Not Acceptable.\n The requested media type is not supported"), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Server error occurred while fetching the " + +// "list of supported device types.", +// response = ErrorResponse.class) +// } +// ) +// Response deployDeviceTypeEventDefinition( +// @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") +// @PathParam("type")String deviceType, +// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") +// @QueryParam("skipPersist") boolean skipPersist, +// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") +// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, +// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", +// required = true) +// @Valid DeviceTypeEvent deviceTypeEvent); @DELETE @Path("/{type}") @@ -178,183 +179,186 @@ public interface DeviceEventManagementService { "ios, and windows.", required = false) @PathParam("type")String deviceType); - @GET - @Path("/{type}/{deviceId}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Device Events", - notes = "Get the events for the device.", - tags = "Device Event Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched the event definition.", - response = EventRecords.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = - "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - } - ), - @ApiResponse( - code = 400, - message = - "Bad Request. \n"), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the " + - "list of supported device types.", - response = ErrorResponse.class) - } - ) - Response getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false) - @PathParam("deviceId") String deviceId, - @ApiParam(name = "from", value = "unix timestamp to retrieve", required = false) - @QueryParam("from") long from, - @ApiParam(name = "to", value = "unix time to retrieve", required = false) - @QueryParam("to") long to, - @ApiParam(name = "type", value = "name of the device type", required = false) - @PathParam("type") String deviceType, - @ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false) - @QueryParam("offset") int offset, - @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) - @QueryParam("limit") int limit); + //todo:amalka +// @GET +// @Path("/{type}/{deviceId}") +// @ApiOperation( +// produces = MediaType.APPLICATION_JSON, +// httpMethod = "GET", +// value = "Getting Device Events", +// notes = "Get the events for the device.", +// tags = "Device Event Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// }) +// } +// ) +// @ApiResponses( +// value = { +// @ApiResponse( +// code = 200, +// message = "OK. \n Successfully fetched the event definition.", +// response = EventRecords.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "ETag", +// description = "Entity Tag of the response resource.\n" + +// "Used by caches, or in conditional requests."), +// @ResponseHeader( +// name = "Last-Modified", +// description = +// "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests."), +// } +// ), +// @ApiResponse( +// code = 400, +// message = +// "Bad Request. \n"), +// @ApiResponse( +// code = 406, +// message = "Not Acceptable.\n The requested media type is not supported"), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Server error occurred while fetching the " + +// "list of supported device types.", +// response = ErrorResponse.class) +// } +// ) +// Response getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false) +// @PathParam("deviceId") String deviceId, +// @ApiParam(name = "from", value = "unix timestamp to retrieve", required = false) +// @QueryParam("from") long from, +// @ApiParam(name = "to", value = "unix time to retrieve", required = false) +// @QueryParam("to") long to, +// @ApiParam(name = "type", value = "name of the device type", required = false) +// @PathParam("type") String deviceType, +// @ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false) +// @QueryParam("offset") int offset, +// @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) +// @QueryParam("limit") int limit); - @GET - @Path("last-known/{type}/{deviceId}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Last Known Device Events", - notes = "Get the last known events for the device.", - tags = "Device Event Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched the event.", - response = EventRecords.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = - "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - } - ), - @ApiResponse( - code = 400, - message = - "Bad Request. \n"), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the " + - "list of supported device types.", - response = ErrorResponse.class) - } - ) - Response getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = true) - @PathParam("deviceId") String deviceId, - @ApiParam(name = "type", value = "name of the device type", required = true) - @PathParam("type") String deviceType, - @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) - @QueryParam("limit") int limit); + //todo:amalka +// @GET +// @Path("last-known/{type}/{deviceId}") +// @ApiOperation( +// produces = MediaType.APPLICATION_JSON, +// httpMethod = "GET", +// value = "Getting Last Known Device Events", +// notes = "Get the last known events for the device.", +// tags = "Device Event Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// }) +// } +// ) +// @ApiResponses( +// value = { +// @ApiResponse( +// code = 200, +// message = "OK. \n Successfully fetched the event.", +// response = EventRecords.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "ETag", +// description = "Entity Tag of the response resource.\n" + +// "Used by caches, or in conditional requests."), +// @ResponseHeader( +// name = "Last-Modified", +// description = +// "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests."), +// } +// ), +// @ApiResponse( +// code = 400, +// message = +// "Bad Request. \n"), +// @ApiResponse( +// code = 406, +// message = "Not Acceptable.\n The requested media type is not supported"), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Server error occurred while fetching the " + +// "list of supported device types.", +// response = ErrorResponse.class) +// } +// ) +// Response getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = true) +// @PathParam("deviceId") String deviceId, +// @ApiParam(name = "type", value = "name of the device type", required = true) +// @PathParam("type") String deviceType, +// @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) +// @QueryParam("limit") int limit); - @GET - @Path("filter/{type}/{parameter}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting the filtered devices", - notes = "Get the list of devices based on the filter parameter", - tags = "Device Event Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched the event.", - response = EventRecords.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = - "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - } - ), - @ApiResponse( - code = 400, - message = - "Bad Request. \n"), - @ApiResponse( - code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the " + - "list of supported device types.", - response = ErrorResponse.class) - } - ) - Response getFilteredDevices( - @ApiParam(name = "type", value = "name of the device type", required = true) - @PathParam("type") String deviceType, - @ApiParam(name = "type", value = "name of the parameter", required = true) - @PathParam("type") String parameter, - @ApiParam(name = "limit", value = "minimum value the parameter can have", required = false) - @QueryParam("min") double min, - @ApiParam(name = "max", value = "max value the parameter can have", required = false) - @QueryParam("max") double max - ); + //todo:amalka +// @GET +// @Path("filter/{type}/{parameter}") +// @ApiOperation( +// produces = MediaType.APPLICATION_JSON, +// httpMethod = "GET", +// value = "Getting the filtered devices", +// notes = "Get the list of devices based on the filter parameter", +// tags = "Device Event Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") +// }) +// } +// ) +// @ApiResponses( +// value = { +// @ApiResponse( +// code = 200, +// message = "OK. \n Successfully fetched the event.", +// response = EventRecords.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "ETag", +// description = "Entity Tag of the response resource.\n" + +// "Used by caches, or in conditional requests."), +// @ResponseHeader( +// name = "Last-Modified", +// description = +// "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests."), +// } +// ), +// @ApiResponse( +// code = 400, +// message = +// "Bad Request. \n"), +// @ApiResponse( +// code = 406, +// message = "Not Acceptable.\n The requested media type is not supported"), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Server error occurred while fetching the " + +// "list of supported device types.", +// response = ErrorResponse.class) +// } +// ) +// Response getFilteredDevices( +// @ApiParam(name = "type", value = "name of the device type", required = true) +// @PathParam("type") String deviceType, +// @ApiParam(name = "type", value = "name of the parameter", required = true) +// @PathParam("type") String parameter, +// @ApiParam(name = "limit", value = "minimum value the parameter can have", required = false) +// @QueryParam("min") double min, +// @ApiParam(name = "max", value = "max value the parameter can have", required = false) +// @QueryParam("max") double max +// ); @GET @Path("/{type}") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index f90a205c0a..01145b05ec 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -269,6 +269,12 @@ public interface DeviceManagementService { @QueryParam("ownership") @Size(max = 45) String ownership, + @ApiParam( + name = "serialNumber", + value = "The serial number of the device.", + required = false) + @QueryParam("serialNumber") + String serialNumber, @ApiParam( name = "status", value = "Provide the device status details, such as active or inactive.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java index 5e55acdc77..a0cd0854c4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java @@ -16,7 +16,6 @@ * under the License. */ - package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.Api; @@ -32,6 +31,7 @@ import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.geo.service.Alert; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper; @@ -41,7 +41,6 @@ import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; @@ -51,7 +50,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.ArrayList; +import java.util.List; @SwaggerDefinition( info = @Info( @@ -97,71 +96,72 @@ public interface GeoLocationBasedService { /** * Retrieve Analytics for the device type */ - @GET - @Path("stats/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Getting the Location Details of a Device", - notes = "Get the location details of a device during a define time period.", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers found.", - response = Response.class), - @ApiResponse( - code = 401, - message = "Unauthorized. \n Unauthorized request."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Error on retrieving stats", - response = Response.class) - }) - Response getGeoDeviceStats( - @ApiParam( - name = "deviceId", - value = "The device ID.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android, or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "from", - value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", - required = true) - @QueryParam("from") long from, - @ApiParam( - name = "to", - value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", - required = true) - @QueryParam("to") long to); + //todo:amalka +// @GET +// @Path("stats/{deviceType}/{deviceId}") +// @ApiOperation( +// consumes = "application/json", +// produces = "application/json", +// httpMethod = "GET", +// value = "Getting the Location Details of a Device", +// notes = "Get the location details of a device during a define time period.", +// response = Response.class, +// tags = "Geo Service Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") +// }) +// } +// ) +// @ApiResponses(value = { +// @ApiResponse( +// code = 200, +// message = "OK.", +// response = Response.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "Last-Modified", +// description = "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests."), +// }), +// @ApiResponse( +// code = 400, +// message = "Bad Request. \n Invalid Device Identifiers found.", +// response = Response.class), +// @ApiResponse( +// code = 401, +// message = "Unauthorized. \n Unauthorized request."), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Error on retrieving stats", +// response = Response.class) +// }) +// Response getGeoDeviceStats( +// @ApiParam( +// name = "deviceId", +// value = "The device ID.", +// required = true) +// @PathParam("deviceId") String deviceId, +// @ApiParam( +// name = "device-type", +// value = "The device type, such as ios, android, or windows.", +// required = true) +// @PathParam("deviceType") +// @Size(max = 45) +// String deviceType, +// @ApiParam( +// name = "from", +// value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", +// required = true) +// @QueryParam("from") long from, +// @ApiParam( +// name = "to", +// value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", +// required = true) +// @QueryParam("to") long to); /** * Get data to show device locations in a map @@ -208,6 +208,7 @@ public interface GeoLocationBasedService { message = "Internal Server Error. \n Error on retrieving stats", response = Response.class) }) + @Deprecated Response getGeoDeviceLocations( @ApiParam( name = "deviceType", @@ -244,6 +245,124 @@ public interface GeoLocationBasedService { defaultValue ="2") @QueryParam("zoom") int zoom); + @Path("stats/geo-view") + @GET + @Consumes("application/json") + @Produces("application/json") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Getting geo view of devices", + notes = "Get the details of the devices that are within the map. The map area is enclosed with four " + + "coordinates in the shape of a square or rectangle. This is done by defining two points of the " + + "map. The other two points are automatically created using the given points. " + + "You can define the zoom level or scale of the map too.", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid parameters found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeoDeviceView( + @ApiParam( + name = "minLat", + value = "Define the minimum latitude of the geofence.", + required = true, + defaultValue ="79.85213577747345") + @QueryParam("minLat") double minLat, + @ApiParam( + name = "maxLat", + value = "Define the maximum latitude of the geofence.", + required = true, + defaultValue ="79.85266149044037") + @QueryParam("maxLat") double maxLat, + @ApiParam( + name = "minLong", + value = "Define the minimum longitude of the geofence.", + required = true, + defaultValue ="6.909673257977737") + @QueryParam("minLong") double minLong, + @ApiParam( + name = "maxLong", + value = "Define the maximum longitude of the geofence", + required = true, + defaultValue ="6.909673257977737") + @QueryParam("maxLong") double maxLong, + @ApiParam( + name = "zoom", + value = "Define the level to zoom or scale the map. You can define any value between 1 to 14.", + required = true, + defaultValue ="2") + @QueryParam("zoom") int zoom, + @ApiParam( + name = "deviceType", + value = "Optional Device type name.") + @QueryParam("deviceType") List deviceTypes, + @ApiParam( + name = "deviceIdentifier", + value = "Optional Device Identifier.") + @QueryParam("deviceIdentifier") List deviceIdentifiers, + @ApiParam( + name = "status", + value = "Optional Device status.") + @QueryParam("status") List statuses, + @ApiParam( + name = "ownership", + value = "Optional Device ownership.") + @QueryParam("ownership") List ownerships, + @ApiParam( + name = "owner", + value = "Optional Device owner.") + @QueryParam("owner") List owners, + @ApiParam( + name = "noClusters", + value = "Optional include devices only.") + @QueryParam("noClusters") boolean noClusters, + @ApiParam( + name = "createdBefore", + value = "Optional Device created before timestamp.") + @QueryParam("createdBefore") long createdBefore, + @ApiParam( + name = "createdAfter", + value = "Optional Device created after timestamp..") + @QueryParam("createdAfter") long createdAfter, + @ApiParam( + name = "updatedBefore", + value = "Optional Device updated before timestamp.") + @QueryParam("updatedBefore") long updatedBefore, + @ApiParam( + name = "updatedAfter", + value = "Optional Device updated after timestamp.") + @QueryParam("updatedAfter") long updatedAfter); /** * Create Geo alerts @@ -602,128 +721,130 @@ public interface GeoLocationBasedService { /** * Retrieve Geo alerts history */ - @GET - @Path("alerts/history/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Getting the Geo Service Alert History of a Device", - notes = "Get the geo alert history of a device during the defined time period.", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers found.", - response = Response.class), - @ApiResponse( - code = 401, - message = "Unauthorized. \n Unauthorized request."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Error on retrieving stats", - response = Response.class) - }) - Response getGeoAlertsHistory( - @ApiParam( - name = "deviceId", - value = "The device ID.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android, or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "from", - value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", - required = true) - @QueryParam("from") long from, - @ApiParam( - name = "to", - value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", - required = true) - @QueryParam("to") long to); + //todo:amalka +// @GET +// @Path("alerts/history/{deviceType}/{deviceId}") +// @ApiOperation( +// consumes = "application/json", +// produces = "application/json", +// httpMethod = "GET", +// value = "Getting the Geo Service Alert History of a Device", +// notes = "Get the geo alert history of a device during the defined time period.", +// response = Response.class, +// tags = "Geo Service Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") +// }) +// } +// ) +// @ApiResponses(value = { +// @ApiResponse( +// code = 200, +// message = "OK.", +// response = Response.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "Last-Modified", +// description = "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests.") +// }), +// @ApiResponse( +// code = 400, +// message = "Bad Request. \n Invalid Device Identifiers found.", +// response = Response.class), +// @ApiResponse( +// code = 401, +// message = "Unauthorized. \n Unauthorized request."), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Error on retrieving stats", +// response = Response.class) +// }) +// Response getGeoAlertsHistory( +// @ApiParam( +// name = "deviceId", +// value = "The device ID.", +// required = true) +// @PathParam("deviceId") String deviceId, +// @ApiParam( +// name = "device-type", +// value = "The device type, such as ios, android, or windows.", +// required = true) +// @PathParam("deviceType") +// @Size(max = 45) +// String deviceType, +// @ApiParam( +// name = "from", +// value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", +// required = true) +// @QueryParam("from") long from, +// @ApiParam( +// name = "to", +// value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", +// required = true) +// @QueryParam("to") long to); /** * Retrieve Geo alerts history for geo clusters */ - @GET - @Path("alerts/history") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Retrieve Geo alerts history for geo clusters", - notes = "Retrieving geo alert history of all defined alerts for geo clusters", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers found.", - response = Response.class), - @ApiResponse( - code = 401, - message = "Unauthorized. \n Unauthorized request."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Error on retrieving stats", - response = Response.class) - }) - Response getGeoAlertsHistoryForGeoClusters( - @ApiParam( - name = "from", - value = "Get stats from what time", - required = true) - @QueryParam("from") long from, - @ApiParam( - name = "to", - value = "Get stats up to what time", - required = true) - @QueryParam("to") long to); + //todo:amalka +// @GET +// @Path("alerts/history") +// @ApiOperation( +// consumes = "application/json", +// produces = "application/json", +// httpMethod = "GET", +// value = "Retrieve Geo alerts history for geo clusters", +// notes = "Retrieving geo alert history of all defined alerts for geo clusters", +// response = Response.class, +// tags = "Geo Service Management", +// extensions = { +// @Extension(properties = { +// @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") +// }) +// } +// ) +// @ApiResponses(value = { +// @ApiResponse( +// code = 200, +// message = "OK.", +// response = Response.class, +// responseHeaders = { +// @ResponseHeader( +// name = "Content-Type", +// description = "The content type of the body"), +// @ResponseHeader( +// name = "Last-Modified", +// description = "Date and time the resource was last modified.\n" + +// "Used by caches, or in conditional requests.") +// }), +// @ApiResponse( +// code = 400, +// message = "Bad Request. \n Invalid Device Identifiers found.", +// response = Response.class), +// @ApiResponse( +// code = 401, +// message = "Unauthorized. \n Unauthorized request."), +// @ApiResponse( +// code = 500, +// message = "Internal Server Error. \n Error on retrieving stats", +// response = Response.class) +// }) +// Response getGeoAlertsHistoryForGeoClusters( +// @ApiParam( +// name = "from", +// value = "Get stats from what time", +// required = true) +// @QueryParam("from") long from, +// @ApiParam( +// name = "to", +// value = "Get stats up to what time", +// required = true) +// @QueryParam("to") long to); /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index f759ed13a9..47126e22da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -26,7 +26,6 @@ import org.apache.axis2.AxisFault; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; @@ -36,7 +35,6 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; 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.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -52,7 +50,6 @@ import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; -import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.user.api.UserStoreException; @@ -280,19 +277,20 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { i++; } - if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type - , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) - , Constants.DEFAULT_STREAM_VERSION, metaData - , null, payloadData)) { + // todo: amalka: commented data publishing +// if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type +// , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) +// , Constants.DEFAULT_STREAM_VERSION, metaData +// , null, payloadData)) { return Response.status(Response.Status.OK).build(); - } else { - String msg = "Error occurred while publishing the event."; - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } catch (DataPublisherConfigurationException e) { - String msg = "Error occurred while publishing the event."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); +// } else { +// String msg = "Error occurred while publishing the event."; +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); +// } +// } catch (DataPublisherConfigurationException e) { +// String msg = "Error occurred while publishing the event."; +// log.error(msg, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceAccessAuthorizationException e) { String msg = "Error occurred when checking for authorization"; log.error(msg, e); @@ -380,19 +378,20 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { i++; } - if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type - , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) - , Constants.DEFAULT_STREAM_VERSION, metaData - , null, payloadData)) { + // todo: amalka: commented data publishing +// if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type +// , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) +// , Constants.DEFAULT_STREAM_VERSION, metaData +// , null, payloadData)) { return Response.status(Response.Status.OK).build(); - } else { - String msg = "Error occurred while publishing the event."; - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } catch (DataPublisherConfigurationException e) { - String msg = "Error occurred while publishing the event."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); +// } else { +// String msg = "Error occurred while publishing the event."; +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); +// } +// } catch (DataPublisherConfigurationException e) { +// String msg = "Error occurred while publishing the event."; +// log.error(msg, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (DeviceAccessAuthorizationException e) { String msg = "Error occurred when checking for authorization"; log.error(msg, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java index 6c04581110..eda7ee4822 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java @@ -4,29 +4,13 @@ import org.apache.axis2.AxisFault; import org.apache.axis2.client.Stub; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -import org.wso2.carbon.analytics.dataservice.commons.SortByField; -import org.wso2.carbon.analytics.dataservice.commons.SortType; -import org.wso2.carbon.analytics.datasource.commons.Record; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException; -import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; -import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable; -import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList; -import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventRecords; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; @@ -43,21 +27,14 @@ import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; -import javax.validation.Valid; import javax.ws.rs.DELETE; import javax.ws.rs.GET; -import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.rmi.RemoteException; import java.util.ArrayList; -import java.util.Calendar; -import java.util.Comparator; -import java.util.HashSet; import java.util.List; -import java.util.Set; /** @@ -81,49 +58,50 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe private static final String MQTT_CONTENT_VALIDATOR = "default"; private static final String TIMESTAMP_FIELD_NAME = "_timestamp"; - private static AnalyticsDataAPI getAnalyticsDataAPI() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - AnalyticsDataAPI analyticsDataAPI = - (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); - if (analyticsDataAPI == null) { - String msg = "Analytics api service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return analyticsDataAPI; - } + //todo:amalka +// private static AnalyticsDataAPI getAnalyticsDataAPI() { +// PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); +// AnalyticsDataAPI analyticsDataAPI = +// (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); +// if (analyticsDataAPI == null) { +// String msg = "Analytics api service has not initialized."; +// log.error(msg); +// throw new IllegalStateException(msg); +// } +// return analyticsDataAPI; +// } - private static EventRecords getAllEventsForDevice(String tableName, String query, List sortByFields - , int offset, int limit) throws AnalyticsException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); - EventRecords eventRecords = new EventRecords(); - int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); - if (eventCount == 0) { - eventRecords.setCount(0); - } - List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit, - sortByFields); - List recordIds = getRecordIds(resultEntries); - AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); - eventRecords.setCount(eventCount); - List records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response); - records.sort(new Comparator() { - @Override public int compare(Record r1, Record r2) { - return Long.compare(r2.getTimestamp(), r1.getTimestamp()); - } - }); - eventRecords.setList(records); - return eventRecords; - } +// private static EventRecords getAllEventsForDevice(String tableName, String query, List sortByFields +// , int offset, int limit) throws AnalyticsException { +// int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); +// AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); +// EventRecords eventRecords = new EventRecords(); +// int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); +// if (eventCount == 0) { +// eventRecords.setCount(0); +// } +// List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit, +// sortByFields); +// List recordIds = getRecordIds(resultEntries); +// AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); +// eventRecords.setCount(eventCount); +// List records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response); +// records.sort(new Comparator() { +// @Override public int compare(Record r1, Record r2) { +// return Long.compare(r2.getTimestamp(), r1.getTimestamp()); +// } +// }); +// eventRecords.setList(records); +// return eventRecords; +// } - private static List getRecordIds(List searchResults) { - List ids = new ArrayList<>(); - for (SearchResultEntry searchResult : searchResults) { - ids.add(searchResult.getId()); - } - return ids; - } +// private static List getRecordIds(List searchResults) { +// List ids = new ArrayList<>(); +// for (SearchResultEntry searchResult : searchResults) { +// ids.add(searchResult.getId()); +// } +// return ids; +// } /** * Retrieves the stream definition from das for the given device type. @@ -195,65 +173,66 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe /** * Deploy Event Stream, Receiver, Publisher and Store Configuration. */ - @POST - @Path("/{type}") - @Override - public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, - @QueryParam("skipPersist") boolean skipPersist, - @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, - @Valid DeviceTypeEvent deviceTypeEvent) { - TransportType transportType = deviceTypeEvent.getTransportType(); - EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList(); - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - try { - if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || - deviceType == null || transportType == null || - !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { - String errorMessage = "Invalid Payload"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); - String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; - publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); - publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); - if (!skipPersist) { - publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); - } - publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( - MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { - publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); - publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); - } - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - return Response.ok().build(); - } catch (AxisFault e) { - log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (RemoteException e) { - log.error("Failed to connect with the remote services:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (JWTClientException e) { - log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (UserStoreException e) { - log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (DeviceManagementException e) { - log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { - log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, - e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } + //todo:amalka +// @POST +// @Path("/{type}") +// @Override +// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, +// @QueryParam("skipPersist") boolean skipPersist, +// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, +// @Valid DeviceTypeEvent deviceTypeEvent) { +// TransportType transportType = deviceTypeEvent.getTransportType(); +// EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList(); +// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); +// try { +// if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || +// deviceType == null || transportType == null || +// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { +// String errorMessage = "Invalid Payload"; +// log.error(errorMessage); +// return Response.status(Response.Status.BAD_REQUEST).build(); +// } +// String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); +// String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; +// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); +// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); +// if (!skipPersist) { +// publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); +// } +// publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); +// try { +// PrivilegedCarbonContext.startTenantFlow(); +// PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( +// MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); +// if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { +// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); +// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); +// } +// } finally { +// PrivilegedCarbonContext.endTenantFlow(); +// } +// return Response.ok().build(); +// } catch (AxisFault e) { +// log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (RemoteException e) { +// log.error("Failed to connect with the remote services:" + tenantDomain, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (JWTClientException e) { +// log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (UserStoreException e) { +// log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (DeviceManagementException e) { +// log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { +// log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, +// e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } +// } /** * Delete device type specific artifacts from DAS. @@ -349,175 +328,178 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe /** * Returns device specific data for the give period of time. */ - @GET - @Path("/{type}/{deviceId}") - @Override - public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, - @QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset") - int offset, @QueryParam("limit") int limit) { - if (from == 0 || to == 0) { - String errorMessage = "Invalid values for from/to"; - return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); - } - if (limit == 0) { - String errorMessage = "Invalid values for offset/limit"; - return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); - } - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId - + " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); - try { - if (deviceType == null || - !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { - String errorMessage = "Invalid device type"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType))) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); - sortByFields.add(sortByField); - EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit); - return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); - } catch (AnalyticsException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (DeviceManagementException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } - } + //todo:amalka +// @GET +// @Path("/{type}/{deviceId}") +// @Override +// public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, +// @QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset") +// int offset, @QueryParam("limit") int limit) { +// if (from == 0 || to == 0) { +// String errorMessage = "Invalid values for from/to"; +// return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); +// } +// if (limit == 0) { +// String errorMessage = "Invalid values for offset/limit"; +// return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); +// } +// String fromDate = String.valueOf(from); +// String toDate = String.valueOf(to); +// String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId +// + " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; +// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); +// String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); +// try { +// if (deviceType == null || +// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { +// String errorMessage = "Invalid device type"; +// log.error(errorMessage); +// return Response.status(Response.Status.BAD_REQUEST).build(); +// } +// if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( +// new DeviceIdentifier(deviceId, deviceType))) { +// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); +// } +// List sortByFields = new ArrayList<>(); +// SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); +// sortByFields.add(sortByField); +// EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit); +// return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); +// } catch (AnalyticsException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } catch (DeviceAccessAuthorizationException e) { +// log.error(e.getErrorMessage(), e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (DeviceManagementException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } +// } /** * Returns last known data points up to the limit if limit is specified. Otherwise returns last known data point. * Limit parameter needs to be zero or positive. */ - @GET - @Path("/last-known/{type}/{deviceId}") - @Override - public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType, @QueryParam("limit") int limit) { - String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId; - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); - try { - if (deviceType == null || - !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { - String errorMessage = "Invalid device type"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType))) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); - sortByFields.add(sortByField); - if (limit == 0) { - EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1); - return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); - } else if (limit > 0) { - EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, limit); - return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); - } else { - String errorMessage = "Invalid limit value"; - return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); - } - } catch (AnalyticsException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (DeviceManagementException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } - } + //todo:amalka +// @GET +// @Path("/last-known/{type}/{deviceId}") +// @Override +// public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType, @QueryParam("limit") int limit) { +// String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId; +// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); +// String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); +// try { +// if (deviceType == null || +// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { +// String errorMessage = "Invalid device type"; +// log.error(errorMessage); +// return Response.status(Response.Status.BAD_REQUEST).build(); +// } +// if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( +// new DeviceIdentifier(deviceId, deviceType))) { +// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); +// } +// List sortByFields = new ArrayList<>(); +// SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); +// sortByFields.add(sortByField); +// if (limit == 0) { +// EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1); +// return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); +// } else if (limit > 0) { +// EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, limit); +// return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); +// } else { +// String errorMessage = "Invalid limit value"; +// return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); +// } +// } catch (AnalyticsException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } catch (DeviceAccessAuthorizationException e) { +// log.error(e.getErrorMessage(), e); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +// } catch (DeviceManagementException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } +// } /** * Returns the filterd device list. Devices are filterd using the paramter given and the timestamp of the record. * parameter should given as a range. */ - @GET - @Path("filter/{type}/{parameter}") - @Override - public Response getFilteredDevices(@PathParam("type") String deviceType, @PathParam("parameter") String parameter, - @QueryParam("min") double min, @QueryParam("max") double max) { - String query; - Calendar c = java.util.Calendar.getInstance(); - long currentTimestamp = c.getTimeInMillis(); - long previousTimestamp = currentTimestamp - 300 * 1000; - String fromDate = String.valueOf(previousTimestamp); - String toDate = String.valueOf(currentTimestamp); - if (min != 0 & max != 0) { - query = parameter + " : [" + min + " TO " + max + "]" + - " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; - } else { - String errorMessage = "The of range values need to be given"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); - try { - if (deviceType == null || - !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { - String errorMessage = "Invalid device type"; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).build(); - } - - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); - sortByFields.add(sortByField); - EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 100); - List filterdEvents = eventRecords.getRecord(); - List uniqueFilterdEvents = new ArrayList(); - Set devices = new HashSet<>(); - - for (int i = 0; i < filterdEvents.size(); i++) { - String deviceid = (String) filterdEvents.get(i).getValue("meta_deviceId"); - if (!devices.contains(deviceid) && DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceid, deviceType))) { - devices.add(deviceid); - uniqueFilterdEvents.add(filterdEvents.get(i)); - } - } - - EventRecords filterdRecords = new EventRecords(); - filterdRecords.setList(uniqueFilterdEvents); - return Response.status(Response.Status.OK.getStatusCode()).entity(filterdRecords).build(); - - } catch (AnalyticsException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceManagementException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceAccessAuthorizationException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - } + //todo:amalka +// @GET +// @Path("filter/{type}/{parameter}") +// @Override +// public Response getFilteredDevices(@PathParam("type") String deviceType, @PathParam("parameter") String parameter, +// @QueryParam("min") double min, @QueryParam("max") double max) { +// String query; +// Calendar c = java.util.Calendar.getInstance(); +// long currentTimestamp = c.getTimeInMillis(); +// long previousTimestamp = currentTimestamp - 300 * 1000; +// String fromDate = String.valueOf(previousTimestamp); +// String toDate = String.valueOf(currentTimestamp); +// if (min != 0 & max != 0) { +// query = parameter + " : [" + min + " TO " + max + "]" + +// " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; +// } else { +// String errorMessage = "The of range values need to be given"; +// log.error(errorMessage); +// return Response.status(Response.Status.BAD_REQUEST).build(); +// } +// +// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); +// String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); +// try { +// if (deviceType == null || +// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { +// String errorMessage = "Invalid device type"; +// log.error(errorMessage); +// return Response.status(Response.Status.BAD_REQUEST).build(); +// } +// +// List sortByFields = new ArrayList<>(); +// SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); +// sortByFields.add(sortByField); +// EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 100); +// List filterdEvents = eventRecords.getRecord(); +// List uniqueFilterdEvents = new ArrayList(); +// Set devices = new HashSet<>(); +// +// for (int i = 0; i < filterdEvents.size(); i++) { +// String deviceid = (String) filterdEvents.get(i).getValue("meta_deviceId"); +// if (!devices.contains(deviceid) && DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( +// new DeviceIdentifier(deviceid, deviceType))) { +// devices.add(deviceid); +// uniqueFilterdEvents.add(filterdEvents.get(i)); +// } +// } +// +// EventRecords filterdRecords = new EventRecords(); +// filterdRecords.setList(uniqueFilterdEvents); +// return Response.status(Response.Status.OK.getStatusCode()).entity(filterdRecords).build(); +// +// } catch (AnalyticsException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } catch (DeviceManagementException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); +// } catch (DeviceAccessAuthorizationException e) { +// String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; +// log.error(errorMsg); +// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); +// } +// } private void publishEventReceivers(String streamNameWithVersion, TransportType transportType @@ -613,47 +595,48 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe } } - private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes) - throws RemoteException, UserStoreException, JWTClientException, - EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException { - EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = - DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub(); - try { - AnalyticsTable analyticsTable = new AnalyticsTable(); - analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME); - analyticsTable.setStreamVersion(version); - analyticsTable.setTableName(streamName); - analyticsTable.setMergeSchema(false); - analyticsTable.setPersist(true); - AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1]; - int i = 0; - for (Attribute attribute : eventAttributes.getList()) { - AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); - analyticsTableRecord.setColumnName(attribute.getName()); - analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase()); - analyticsTableRecord.setFacet(false); - analyticsTableRecord.setIndexed(false); - analyticsTableRecord.setPersist(true); - analyticsTableRecord.setPrimaryKey(false); - analyticsTableRecord.setScoreParam(false); - analyticsTableRecords[i] = analyticsTableRecord; - i++; - } - AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); - analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE); - analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase()); - analyticsTableRecord.setFacet(false); - analyticsTableRecord.setIndexed(true); - analyticsTableRecord.setPersist(true); - analyticsTableRecord.setPrimaryKey(false); - analyticsTableRecord.setScoreParam(false); - analyticsTableRecords[i] = analyticsTableRecord; - analyticsTable.setAnalyticsTableRecords(analyticsTableRecords); - eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable); - } finally { - cleanup(eventStreamPersistenceAdminServiceStub); - } - } + //todo:amalka +// private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes) +// throws RemoteException, UserStoreException, JWTClientException, +// EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException { +// EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = +// DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub(); +// try { +// AnalyticsTable analyticsTable = new AnalyticsTable(); +// analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME); +// analyticsTable.setStreamVersion(version); +// analyticsTable.setTableName(streamName); +// analyticsTable.setMergeSchema(false); +// analyticsTable.setPersist(true); +// AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1]; +// int i = 0; +// for (Attribute attribute : eventAttributes.getList()) { +// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); +// analyticsTableRecord.setColumnName(attribute.getName()); +// analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase()); +// analyticsTableRecord.setFacet(false); +// analyticsTableRecord.setIndexed(false); +// analyticsTableRecord.setPersist(true); +// analyticsTableRecord.setPrimaryKey(false); +// analyticsTableRecord.setScoreParam(false); +// analyticsTableRecords[i] = analyticsTableRecord; +// i++; +// } +// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); +// analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE); +// analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase()); +// analyticsTableRecord.setFacet(false); +// analyticsTableRecord.setIndexed(true); +// analyticsTableRecord.setPersist(true); +// analyticsTableRecord.setPrimaryKey(false); +// analyticsTableRecord.setScoreParam(false); +// analyticsTableRecords[i] = analyticsTableRecord; +// analyticsTable.setAnalyticsTableRecords(analyticsTableRecords); +// eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable); +// } finally { +// cleanup(eventStreamPersistenceAdminServiceStub); +// } +// } private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType) throws RemoteException, UserStoreException, JWTClientException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index b2f2d1ab11..7648a102b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -172,6 +172,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("userPattern") String userPattern, @QueryParam("role") String role, @QueryParam("ownership") String ownership, + @QueryParam("serialNumber") String serialNumber, @QueryParam("status") List status, @QueryParam("groupId") int groupId, @QueryParam("since") String since, @@ -205,6 +206,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { RequestValidationUtil.validateOwnershipType(ownership); request.setOwnership(ownership); } + if (StringUtils.isNotBlank(serialNumber)) { + request.setSerialNumber(serialNumber); + } if (status != null && !status.isEmpty()) { boolean isStatusEmpty = true; for (String statusString : status){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java index b2c28d8f1e..bafe13d742 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -38,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; @@ -47,13 +48,14 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.geo.service.Alert; import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; import org.wso2.carbon.device.mgt.common.geo.service.Event; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy; import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -81,7 +83,10 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import java.io.IOException; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -91,15 +96,15 @@ import java.util.Map; */ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { - private static Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class); + private static final Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class); @Path("stats/{deviceType}/{deviceId}") @GET @Consumes("application/json") @Produces("application/json") public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @QueryParam("from") long from, @QueryParam("to") long to) { + @PathParam("deviceType") String deviceType, + @QueryParam("from") long from, @QueryParam("to") long to) { try { if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) { return Response.status(Response.Status.BAD_REQUEST.getStatusCode()) @@ -155,6 +160,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @GET @Consumes("application/json") @Produces("application/json") + @Deprecated public Response getGeoDeviceLocations( @QueryParam("deviceType") String deviceType, @QueryParam("minLat") double minLat, @@ -162,6 +168,64 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @QueryParam("minLong") double minLong, @QueryParam("maxLong") double maxLong, @QueryParam("zoom") int zoom) { + GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy(); + GeoCoordinate southWest = new GeoCoordinate(minLat, minLong); + GeoCoordinate northEast = new GeoCoordinate(maxLat, maxLong); + int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom); + DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); + GeoQuery geoQuery = new GeoQuery(southWest, northEast, geohashLength); + if (deviceType != null) { + geoQuery.setDeviceTypes(Collections.singletonList(deviceType)); + } + List geoClusters = new ArrayList<>(); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); + try { + List newClusters = deviceManagementService.findGeoClusters(geoQuery); + org.wso2.carbon.device.mgt.jaxrs.beans.GeoCluster geoCluster; + String deviceIdentification = null; + String deviceName = null; + String lastSeen = null; + for (GeoCluster gc : newClusters) { + if (gc.getDevice() != null) { + deviceIdentification = gc.getDevice().getDeviceIdentifier(); + deviceName = gc.getDevice().getName(); + deviceType = gc.getDevice().getType(); + lastSeen = simpleDateFormat.format(new Date(gc.getDevice() + .getEnrolmentInfo().getDateOfLastUpdate())); + } + geoCluster = new org.wso2.carbon.device.mgt.jaxrs.beans.GeoCluster(gc.getCoordinates(), + gc.getSouthWestBound(), gc.getNorthEastBound(), gc.getCount(), gc.getGeohashPrefix(), + deviceIdentification, deviceName, deviceType, lastSeen); + geoClusters.add(geoCluster); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving geo clusters query: " + new Gson().toJson(geoQuery); + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + return Response.ok().entity(geoClusters).build(); + } + + @Path("stats/geo-view") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeoDeviceView( + @QueryParam("minLat") double minLat, + @QueryParam("maxLat") double maxLat, + @QueryParam("minLong") double minLong, + @QueryParam("maxLong") double maxLong, + @QueryParam("zoom") int zoom, + @QueryParam("deviceType") List deviceTypes, + @QueryParam("deviceIdentifier") List deviceIdentifiers, + @QueryParam("status") List statuses, + @QueryParam("ownership") List ownerships, + @QueryParam("owner") List owners, + @QueryParam("noClusters") boolean noClusters, + @QueryParam("createdBefore") long createdBefore, + @QueryParam("createdAfter") long createdAfter, + @QueryParam("updatedBefore") long updatedBefore, + @QueryParam("updatedAfter") long updatedAfter) { GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy(); GeoCoordinate southWest = new GeoCoordinate(minLat, minLong); @@ -169,15 +233,25 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom); DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); List geoClusters; + GeoQuery geoQuery = new GeoQuery(southWest, northEast, geohashLength); + geoQuery.setDeviceTypes(deviceTypes); + geoQuery.setDeviceIdentifiers(deviceIdentifiers); + geoQuery.setStatuses(statuses); + geoQuery.setOwners(owners); + geoQuery.setOwnerships(ownerships); + geoQuery.setNoClusters(noClusters); + geoQuery.setCreatedBefore(createdBefore); + geoQuery.setCreatedAfter(createdAfter); + geoQuery.setUpdatedBefore(updatedBefore); + geoQuery.setUpdatedAfter(updatedAfter); try { - geoClusters = deviceManagementService.findGeoClusters(deviceType, southWest, northEast, geohashLength); + geoClusters = deviceManagementService.findGeoClusters(geoQuery); } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving geo clusters "; + String msg = "Error occurred while retrieving geo clusters for query: " + new Gson().toJson(geoQuery); log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } return Response.ok().entity(geoClusters).build(); - } @Path("alerts/{alertType}/{deviceType}/{deviceId}") @@ -185,8 +259,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { try { if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( new DeviceIdentifier(deviceId, deviceType), @@ -252,8 +326,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { try { if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( new DeviceIdentifier(deviceId, deviceType), @@ -317,9 +391,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response removeGeoAlerts(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType, - @QueryParam("queryName") String queryName) { + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType, + @QueryParam("queryName") String queryName) { try { if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( new DeviceIdentifier(deviceId, deviceType), @@ -375,8 +449,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response getGeoAlerts(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { + @PathParam("deviceType") String deviceType, + @PathParam("alertType") String alertType) { try { if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( new DeviceIdentifier(deviceId, deviceType), @@ -441,26 +515,26 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { String result = null; switch (alertType) { - case GeoServices.ALERT_TYPE_WITHIN: - alerts = geoService.getWithinAlerts(); - break; - case GeoServices.ALERT_TYPE_EXIT: - alerts = geoService.getExitAlerts(); - break; - case GeoServices.ALERT_TYPE_STATIONARY: - alerts = geoService.getStationaryAlerts(); - break; - case GeoServices.ALERT_TYPE_TRAFFIC: - alerts = geoService.getTrafficAlerts(); - break; - case GeoServices.ALERT_TYPE_SPEED: - result = geoService.getSpeedAlerts(); - return Response.ok().entity(result).build(); - case GeoServices.ALERT_TYPE_PROXIMITY: - result = geoService.getProximityAlerts(); - return Response.ok().entity(result).build(); - default: - throw new GeoLocationBasedServiceException("Invalid Alert Type"); + case GeoServices.ALERT_TYPE_WITHIN: + alerts = geoService.getWithinAlerts(); + break; + case GeoServices.ALERT_TYPE_EXIT: + alerts = geoService.getExitAlerts(); + break; + case GeoServices.ALERT_TYPE_STATIONARY: + alerts = geoService.getStationaryAlerts(); + break; + case GeoServices.ALERT_TYPE_TRAFFIC: + alerts = geoService.getTrafficAlerts(); + break; + case GeoServices.ALERT_TYPE_SPEED: + result = geoService.getSpeedAlerts(); + return Response.ok().entity(result).build(); + case GeoServices.ALERT_TYPE_PROXIMITY: + result = geoService.getProximityAlerts(); + return Response.ok().entity(result).build(); + default: + throw new GeoLocationBasedServiceException("Invalid Alert Type"); } return Response.ok().entity(alerts).build(); @@ -476,8 +550,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @QueryParam("from") long from, @QueryParam("to") long to) { + @PathParam("deviceType") String deviceType, + @QueryParam("from") long from, @QueryParam("to") long to) { String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS"; String fromDate = String.valueOf(from); String toDate = String.valueOf(to); @@ -561,8 +635,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { } private List getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName, - List columns, - List searchResults) throws AnalyticsException { + List columns, + List searchResults) throws AnalyticsException { List ids = getIds(searchResults); List requiredColumns = (columns == null || columns.isEmpty()) ? null : columns; AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids); @@ -572,7 +646,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { } private List getSortedEventBeans(Map eventBeanMap, - List searchResults) { + List searchResults) { List sortedRecords = new ArrayList<>(); for (SearchResultEntry entry : searchResults) { sortedRecords.add(eventBeanMap.get(entry.getId())); @@ -665,7 +739,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response getGeofence(@PathParam("fenceId") int fenceId, - @QueryParam("requireEventData") boolean requireEventData) { + @QueryParam("requireEventData") boolean requireEventData) { try { GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); GeofenceData geofenceData = geoService.getGeoFences(fenceId); @@ -748,9 +822,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response getGeofence(@QueryParam("offset") int offset, - @QueryParam("limit") int limit, - @QueryParam("name") String name, - @QueryParam("requireEventData") boolean requireEventData) { + @QueryParam("limit") int limit, + @QueryParam("name") String name, + @QueryParam("requireEventData") boolean requireEventData) { try { GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); if (offset >= 0 && limit != 0) { @@ -819,8 +893,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { @Consumes("application/json") @Produces("application/json") public Response updateGeofence(GeofenceWrapper geofenceWrapper, - @PathParam("fenceId") int fenceId, - @QueryParam("eventIds") int[] eventIds) { + @PathParam("fenceId") int fenceId, + @QueryParam("eventIds") int[] eventIds) { RequestValidationUtil.validateGeofenceData(geofenceWrapper); RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig()); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java index d326802c2a..19a8e59979 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.jaxrs.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; @@ -64,8 +63,9 @@ public class CredentialManagementResponseBuilder { username = CarbonContext.getThreadLocalCarbonContext().getUsername(); userStoreManager.updateCredential(username, credentials.getNewPassword(), credentials.getOldPassword()); - DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); + //todo:amalka +// DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, +// PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + username + " was successfully changed.").build(); } catch (UserStoreException e) { @@ -108,8 +108,9 @@ public class CredentialManagementResponseBuilder { new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build(); } userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); - DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); + //todo:amalka +// DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, +// PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + username + " was successfully changed.").build(); } catch (UserStoreException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 6a6f5daf88..49a734cdee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -45,31 +45,28 @@ import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; -import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; -import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; +import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.MonitoringOperation; +import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper; -import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService; -import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper; +import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; @@ -171,7 +168,7 @@ public class DeviceMgtAPIUtils { private static KeyStore trustStore; private static char[] keyStorePassword; - private static IntegrationClientService integrationClientService; +// private static IntegrationClientService integrationClientService; private static MetadataManagementService metadataManagementService; private static OTPManagementService otpManagementService; @@ -373,24 +370,6 @@ public class DeviceMgtAPIUtils { return privacyComplianceProvider; } - - public static IntegrationClientService getIntegrationClientService() { - if (integrationClientService == null) { - synchronized (DeviceMgtAPIUtils.class) { - if (integrationClientService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - integrationClientService = (IntegrationClientService) ctx.getOSGiService(IntegrationClientService.class, null); - if (integrationClientService == null) { - String msg = "IntegrationClientService is not initialized"; - log.error(msg); - throw new IllegalStateException(msg); - } - } - } - } - return integrationClientService; - } - /** * Initializing and accessing method for OTPManagementService. * @@ -626,17 +605,18 @@ public class DeviceMgtAPIUtils { return username; } - public static EventsPublisherService getEventPublisherService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - EventsPublisherService eventsPublisherService = - (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); - if (eventsPublisherService == null) { - String msg = "Event Publisher service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return eventsPublisherService; - } + // todo: amalka: commented +// public static EventsPublisherService getEventPublisherService() { +// PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); +// EventsPublisherService eventsPublisherService = +// (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); +// if (eventsPublisherService == null) { +// String msg = "Event Publisher service has not initialized."; +// log.error(msg); +// throw new IllegalStateException(msg); +// } +// return eventsPublisherService; +// } public static String getStreamDefinition(String deviceType, String tenantDomain) { return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", "."); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml index ed2ed21624..60db8782e9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index bb9de05c1f..7b995660ad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -175,7 +175,8 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceAccessAuthorizationService); Response response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -194,19 +195,23 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, true, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, true, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -319,7 +324,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceManagementProviderService); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, - DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS_LIST, 1, + DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); } @@ -339,11 +344,11 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP - , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -365,7 +370,8 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 0, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); } @@ -386,15 +392,18 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, 10, 5); + null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, 10, 5); + null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", false, 10, 5); + null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", + false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -414,15 +423,18 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, since, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 0, since, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, since, null, true, 10, 5); + null, DEFAULT_STATUS_LIST, 0, since, null, true, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); } @@ -444,7 +456,8 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceManagementProviderService); } @@ -466,7 +479,8 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); + null, DEFAULT_STATUS_LIST, 1, null, null, false, + 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java index d19e835848..ebb965fc80 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java @@ -7,8 +7,9 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService; @@ -33,8 +34,9 @@ public class GeoLocationBasedServiceImplTest { @Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are no devices" + "in the given map boundaries") public void testGetGeoDeviceLocations1() throws DeviceManagementException { + GeoQuery geoQuery = new GeoQuery(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); Mockito.doReturn(new ArrayList()).when(deviceManagementProviderService) - .findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); + .findGeoClusters(geoQuery); Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6, 90.1, 6); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -47,12 +49,14 @@ public class GeoLocationBasedServiceImplTest { List geoClusters = new ArrayList<>(); geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7), new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3, - "tb32", "aegtew234", "test1", "android", "1234")); + "tb32", null)); geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1), new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4, - "t1gd", "swerty12s", "t2test", "android", "1234")); + "t1gd", null)); + + GeoQuery geoQuery = new GeoQuery(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); Mockito.doReturn(geoClusters).when(deviceManagementProviderService) - .findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); + .findGeoClusters(geoQuery); Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6, 90.1, 6); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml index eca6c9a3b7..071ebfb39d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -50,7 +50,6 @@ javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", com.fasterxml.jackson.annotation;version="${jackson-annotations.version}", - org.wso2.carbon.analytics.datasource.commons;version="${carbon.analytics.version.range}", io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional, com.google.gson @@ -96,14 +95,6 @@ org.wso2.orbit.com.fasterxml.jackson.core jackson-annotations - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.api - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.datasource.commons - com.google.code.gson gson diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index 94cf5c5272..29bb7922e9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -40,6 +40,7 @@ public class PaginationRequest { private String ownerRole; private Date since; private String filter; + private String serialNumber; private Map property = new HashMap<>(); private List statusList = new ArrayList<>(); private OperationLogFilters operationLogFilters = new OperationLogFilters(); @@ -153,6 +154,10 @@ public class PaginationRequest { return this.property.get(key); } + public String getSerialNumber() { return serialNumber; } + + public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } + public Map getProperties() { Map temp = new HashMap<>(); temp.putAll(property); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCluster.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCluster.java new file mode 100644 index 0000000000..d2bcdc8931 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCluster.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.geo.service; + +import org.wso2.carbon.device.mgt.common.Device; + +public class GeoCluster { + + private final GeoCoordinate coordinates; + private final GeoCoordinate southWestBound; + private final GeoCoordinate northEastBound; + private final long count; + private final String geohashPrefix; + private final Device device; + + public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound, + long count, String geohashPrefix, Device device) { + this.coordinates = coordinates; + this.southWestBound = southWestBound; + this.northEastBound = northEastBound; + this.count = count; + this.geohashPrefix = geohashPrefix; + this.device = device; + } + + public String getGeohashPrefix() { + return geohashPrefix; + } + + public long getCount() { + return count; + } + + public GeoCoordinate getCoordinates() { + return coordinates; + } + + public GeoCoordinate getSouthWestBound() { + return southWestBound; + } + + public GeoCoordinate getNorthEastBound() { + return northEastBound; + } + + public Device getDevice() { + return device; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCoordinate.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCoordinate.java new file mode 100644 index 0000000000..c83d18b1ac --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoCoordinate.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.geo.service; + +public class GeoCoordinate { + + private final double latitude; + private final double longitude; + + public GeoCoordinate(double latitude, double longitude) { + this.latitude = latitude; + this.longitude = longitude; + } + + public double getLatitude() { + return latitude; + } + + public double getLongitude() { + return longitude; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoQuery.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoQuery.java new file mode 100644 index 0000000000..f50e5ae700 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoQuery.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.geo.service; + +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; + +import java.util.List; + +public class GeoQuery { + + private final GeoCoordinate southWest; + private final GeoCoordinate northEast; + private final int geohashLength; + private List deviceTypes; + private List deviceIdentifiers; + private List statuses; + private List ownerships; + private List owners; + private boolean noClusters; + private long createdBefore; + private long createdAfter; + private long updatedBefore; + private long updatedAfter; + + public GeoQuery(GeoCoordinate southWest, GeoCoordinate northEast, int geohashLength) { + this.southWest = southWest; + this.northEast = northEast; + this.geohashLength = geohashLength; + } + + public GeoCoordinate getSouthWest() { + return southWest; + } + + public GeoCoordinate getNorthEast() { + return northEast; + } + + public int getGeohashLength() { + return geohashLength; + } + + public List getDeviceTypes() { + return deviceTypes; + } + + public void setDeviceTypes(List deviceTypes) { + this.deviceTypes = deviceTypes; + } + + public List getDeviceIdentifiers() { + return deviceIdentifiers; + } + + public void setDeviceIdentifiers(List deviceIdentifiers) { + this.deviceIdentifiers = deviceIdentifiers; + } + + public List getStatuses() { + return statuses; + } + + public void setStatuses(List statuses) { + this.statuses = statuses; + } + + public List getOwnerships() { + return ownerships; + } + + public void setOwnerships(List ownerships) { + this.ownerships = ownerships; + } + + public List getOwners() { + return owners; + } + + public void setOwners(List owners) { + this.owners = owners; + } + + public boolean isNoClusters() { + return noClusters; + } + + public void setNoClusters(boolean noClusters) { + this.noClusters = noClusters; + } + + public long getCreatedBefore() { + return createdBefore; + } + + public void setCreatedBefore(long createdBefore) { + this.createdBefore = createdBefore; + } + + public long getCreatedAfter() { + return createdAfter; + } + + public void setCreatedAfter(long createdAfter) { + this.createdAfter = createdAfter; + } + + public long getUpdatedBefore() { + return updatedBefore; + } + + public void setUpdatedBefore(long updatedBefore) { + this.updatedBefore = updatedBefore; + } + + public long getUpdatedAfter() { + return updatedAfter; + } + + public void setUpdatedAfter(long updatedAfter) { + this.updatedAfter = updatedAfter; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java index 1007c18058..234aa084c2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java @@ -30,7 +30,7 @@ import java.util.List; public class ActivityStatus { public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED, NOTNOW } @ApiModelProperty( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/ui/Item.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/ui/Item.java index faf97d7e11..43927eb876 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/ui/Item.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/policy/mgt/ui/Item.java @@ -27,6 +27,7 @@ public class Item { private String label; private String tooltip; + private String docLink; private String key; private String value; private boolean isRequired; @@ -65,6 +66,16 @@ public class Item { this.tooltip = tooltip; } + @XmlElement(name = "DocLink") + public String getDocLink() { + return docLink; + } + + public void setDocLink(String docLink) { + this.docLink = docLink; + } + + @XmlElement(name = "Key", required = true) public String getKey() { return key; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index d9b34a770d..8f78ea3064 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -78,8 +78,8 @@ org.wso2.carbon.device.mgt.core.internal org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.naming, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, @@ -90,7 +90,6 @@ org.wso2.carbon.core, org.wso2.carbon.utils.*, org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.analytics.data.publisher.service, org.wso2.carbon.user.api, org.wso2.carbon.user.core.*, org.wso2.carbon.registry.core.service, @@ -104,8 +103,6 @@ org.wso2.carbon.ndatasource.core, org.wso2.carbon.ntask.core.*, org.wso2.carbon.ntask.common, - org.apache.catalina, - org.apache.catalina.core, org.apache.commons.collections;version="${commons-collections.version.range}", org.wso2.carbon.email.sender.*, io.swagger.annotations.*;resolution:=optional, @@ -122,9 +119,7 @@ org.wso2.carbon.device.mgt.core.* - javax.ws.rs-api, scribe;scope=compile|runtime;inline=false, - javassist;inline=false * @@ -166,32 +161,6 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - - - org.slf4j - slf4j-api - - - javax.servlet - javax.servlet-api - - - org.wso2.carbon.registry - org.wso2.carbon.registry.indexing - - - org.wso2.carbon.identity.framework - org.wso2.carbon.user.mgt - - - commons-lang - commons-lang - - - org.wso2.carbon org.wso2.carbon.logging 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 df5f030684..f29afccfcf 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 @@ -53,6 +53,8 @@ public final class DeviceManagementConstants { public static final String SCOPES_FOR_TOKEN = "perm:device:operations perm:device:publish-event perm:windows:enroll"; public static final String IOT_GATEWAY_HOST = "iot.gateway.host"; public static final String IOT_GATEWAY_HTTPS_PORT = "iot.gateway.https.port"; + public static final String IOT_CORE_HOST = "iot.core.host"; + public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String APPLICATION_REGISTRATION_API_ENDPOINT = "/api-application-registration/register"; public static final String AUTHORIZATION_HEADER = "authorization"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java index 914597687c..1c4a1e91cd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java @@ -31,6 +31,7 @@ public class UIConfiguration { private AppRegistration appRegistration; private List scopes; private boolean isSsoEnable; + private int sessionTimeOut; @XmlElement(name = "AppRegistration", required=true) public AppRegistration getAppRegistration() { @@ -59,4 +60,13 @@ public class UIConfiguration { public void setSsoEnable(boolean ssoEnable) { isSsoEnable = ssoEnable; } + + @XmlElement(name = "SessionTimeOut") + public int getSessionTimeOut() { + return sessionTimeOut; + } + + public void setSessionTimeOut(int sessionTimeOut) { + this.sessionTimeOut = sessionTimeOut; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 38ef50a923..77b9d76c5c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -46,9 +46,10 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import java.sql.SQLException; import java.util.Date; @@ -555,14 +556,11 @@ public interface DeviceDAO { * This method is used to retrieve the details of geoclusters formed relatively to the zoom level and map * boundaries. * - * @param deviceType Optional device type name. - * @param southWest the coordinates of southWest corner of the map. - * @param northEast the coordinates of northEast corner of the map. - * @param tenantId tenant id. + * @param geoQuery the query to determine the geo data. + * @param tenantId tenant id. * @return returns a list of enrolment info objects. */ - List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength,int tenantId) throws DeviceManagementDAOException; + List findGeoClusters(GeoQuery geoQuery, int tenantId) throws DeviceManagementDAOException; /** * This method is used to identify whether given device ids are exist or not. @@ -651,16 +649,14 @@ public interface DeviceDAO { /** * This method is used to get the details of subscribed devices. * - * @param deviceIds device ids of the subscribed devices. - * @param tenantId Id of the current tenant. - * @param offsetValue offset value for get paginated request. - * @param limitValue limit value for get paginated request. - * @param status status of the devices. + * @param deviceIds device ids of the subscribed devices. + * @param tenantId Id of the current tenant. + * @param request paginated request object. * @return devices - subscribed device details list * @throws DeviceManagementDAOException if connections establishment fails. */ - List getSubscribedDevices(int offsetValue, int limitValue, List deviceIds, - int tenantId, List status) throws DeviceManagementDAOException; + List getSubscribedDevices(PaginationRequest request, List deviceIds, int tenantId) + throws DeviceManagementDAOException; /** * @param deviceIds device ids of the subscribed devices. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 749a31e0bb..bf387744e2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -48,13 +48,14 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import java.sql.Connection; import java.sql.PreparedStatement; @@ -64,6 +65,7 @@ import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; @@ -1850,62 +1852,161 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return tenants; } - public List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength, int tenantId) throws DeviceManagementDAOException { + public List findGeoClusters(GeoQuery geoQuery, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; List geoClusters = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE,AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE," + - " MIN(DEVICE_LOCATION.LATITUDE) AS MIN_LATITUDE, MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE," + - " MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE," + - " MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE," + - " SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,?) AS GEOHASH_PREFIX, COUNT(*) AS COUNT," + - " MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION," + - " MIN(DEVICE.NAME) AS NAME," + - " MIN(DEVICE_TYPE.NAME) AS TYPE, " + - " MIN(DEVICE.LAST_UPDATED_TIMESTAMP) AS LAST_UPDATED_TIMESTAMP " + - "FROM DM_DEVICE_LOCATION AS DEVICE_LOCATION,DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE " + - "WHERE DEVICE_LOCATION.LATITUDE BETWEEN ? AND ? AND " + - "DEVICE_LOCATION.LONGITUDE BETWEEN ? AND ? AND " + - "DEVICE.TENANT_ID=? AND " + - "DEVICE.ID=DEVICE_LOCATION.DEVICE_ID AND DEVICE.DEVICE_TYPE_ID=DEVICE_TYPE.ID"; - if (deviceType != null && !deviceType.isEmpty()) { - sql += " AND DEVICE_TYPE.NAME=?"; + String sql = "SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE, " + + "AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE, " + + "MIN(DEVICE_LOCATION.LATITUDE) AS MIN_LATITUDE, " + + "MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE, " + + "MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE, " + + "MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE, " + + "SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,?) AS GEOHASH_PREFIX, " + + "COUNT(DEVICE_LOCATION.ID) AS COUNT, " + + "MIN(DEVICE.ID) AS DEVICE_ID, " + + "MIN(DEVICE.NAME) AS DEVICE_NAME, " + + "MIN(DEVICE.DESCRIPTION) AS DESCRIPTION, " + + "MIN(DEVICE_TYPE.NAME) AS DEVICE_TYPE, " + + "MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION, " + + "MIN(ENROLMENT.ID) AS ENROLMENT_ID, " + + "MIN(ENROLMENT.OWNER) AS OWNER, " + + "MIN(ENROLMENT.OWNERSHIP) AS OWNERSHIP, " + + "MIN(ENROLMENT.IS_TRANSFERRED) AS IS_TRANSFERRED, " + + "MIN(ENROLMENT.DATE_OF_ENROLMENT) AS DATE_OF_ENROLMENT, " + + "MIN(ENROLMENT.DATE_OF_LAST_UPDATE) AS DATE_OF_LAST_UPDATE, " + + "MIN(ENROLMENT.STATUS) AS STATUS " + + "FROM DM_DEVICE_LOCATION AS DEVICE_LOCATION, DM_DEVICE AS DEVICE, " + + "DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT AS ENROLMENT " + + "WHERE DEVICE_LOCATION.LATITUDE BETWEEN ? AND ? " + + "AND DEVICE_LOCATION.LONGITUDE BETWEEN ? AND ? "; + if (geoQuery.getDeviceTypes() != null && !geoQuery.getDeviceTypes().isEmpty()) { + sql += "AND DEVICE_TYPE.NAME IN ("; + sql += String.join(", ", + Collections.nCopies(geoQuery.getDeviceTypes().size(), "?")); + sql += ") "; } - sql += " GROUP BY GEOHASH_PREFIX"; + if (geoQuery.getDeviceIdentifiers() != null && !geoQuery.getDeviceIdentifiers().isEmpty()) { + sql += "AND DEVICE.DEVICE_IDENTIFICATION IN ("; + sql += String.join(", ", + Collections.nCopies(geoQuery.getDeviceIdentifiers().size(), "?")); + sql += ") "; + } + if (geoQuery.getOwners() != null && !geoQuery.getOwners().isEmpty()) { + sql += "AND ENROLMENT.OWNER IN ("; + sql += String.join(", ", + Collections.nCopies(geoQuery.getOwners().size(), "?")); + sql += ") "; + } + if (geoQuery.getOwnerships() != null && !geoQuery.getOwnerships().isEmpty()) { + sql += "AND ENROLMENT.OWNERSHIP IN ("; + sql += String.join(", ", + Collections.nCopies(geoQuery.getOwnerships().size(), "?")); + sql += ") "; + } + if (geoQuery.getStatuses() != null && !geoQuery.getStatuses().isEmpty()) { + sql += "AND ENROLMENT.STATUS IN ("; + sql += String.join(", ", + Collections.nCopies(geoQuery.getStatuses().size(), "?")); + sql += ") "; + } else { + sql += "AND ENROLMENT.STATUS != 'REMOVED' "; + } + if (geoQuery.getCreatedBefore() != 0 || geoQuery.getCreatedAfter() != 0) { + sql += "AND ENROLMENT.DATE_OF_ENROLMENT BETWEEN ? AND ? "; + } + if (geoQuery.getUpdatedBefore() != 0 || geoQuery.getUpdatedAfter() != 0) { + sql += "AND ENROLMENT.DATE_OF_LAST_UPDATE BETWEEN ? AND ? "; + } + sql += "AND DEVICE.ID = DEVICE_LOCATION.DEVICE_ID AND DEVICE.DEVICE_TYPE_ID = DEVICE_TYPE.ID " + + "AND DEVICE.ID = ENROLMENT.DEVICE_ID " + + "AND DEVICE.TENANT_ID = ? AND DEVICE.TENANT_ID = ENROLMENT.TENANT_ID GROUP BY GEOHASH_PREFIX"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, geohashLength); - stmt.setDouble(2, southWest.getLatitude()); - stmt.setDouble(3, northEast.getLatitude()); - stmt.setDouble(4, southWest.getLongitude()); - stmt.setDouble(5, northEast.getLongitude()); - stmt.setDouble(6, tenantId); - if (deviceType != null && !deviceType.isEmpty()) { - stmt.setString(7, deviceType); + + int index = 1; + stmt.setInt(index++, geoQuery.getGeohashLength()); + stmt.setDouble(index++, geoQuery.getSouthWest().getLatitude()); + stmt.setDouble(index++, geoQuery.getNorthEast().getLatitude()); + stmt.setDouble(index++, geoQuery.getSouthWest().getLongitude()); + stmt.setDouble(index++, geoQuery.getNorthEast().getLongitude()); + if (geoQuery.getDeviceTypes() != null) { + for (String s: geoQuery.getDeviceTypes()) { + stmt.setString(index++, s); + } } + if (geoQuery.getDeviceIdentifiers() != null) { + for (String s: geoQuery.getDeviceIdentifiers()) { + stmt.setString(index++, s); + } + } + if (geoQuery.getOwners() != null) { + for (String s: geoQuery.getOwners()) { + stmt.setString(index++, s); + } + } + if (geoQuery.getOwnerships() != null) { + for (String s: geoQuery.getOwnerships()) { + stmt.setString(index++, s); + } + } + if (geoQuery.getStatuses() != null) { + for (Status s: geoQuery.getStatuses()) { + stmt.setString(index++, s.toString()); + } + } + + if (geoQuery.getCreatedBefore() != 0 || geoQuery.getCreatedAfter() != 0) { + stmt.setTimestamp(index++, new Timestamp(geoQuery.getCreatedAfter())); + if (geoQuery.getCreatedBefore() == 0) { + stmt.setTimestamp(index++, new Timestamp(System.currentTimeMillis())); + } else { + stmt.setTimestamp(index++, new Timestamp(geoQuery.getCreatedBefore())); + } + } + if (geoQuery.getUpdatedBefore() != 0 || geoQuery.getUpdatedAfter() != 0) { + stmt.setTimestamp(index++, new Timestamp(geoQuery.getUpdatedAfter())); + if (geoQuery.getUpdatedBefore() == 0) { + stmt.setTimestamp(index++, new Timestamp(System.currentTimeMillis())); + } else { + stmt.setTimestamp(index++, new Timestamp(geoQuery.getUpdatedBefore())); + } + } + stmt.setInt(index, tenantId); + rs = stmt.executeQuery(); + + double latitude; + double longitude; + double minLatitude; + double maxLatitude; + double minLongitude; + double maxLongitude; + long count; + String geohashPrefix; + Device device; while (rs.next()) { - double latitude = rs.getDouble("LATITUDE"); - double longitude = rs.getDouble("LONGITUDE"); - double min_latitude = rs.getDouble("MIN_LATITUDE"); - double max_latitude = rs.getDouble("MAX_LATITUDE"); - double min_longitude = rs.getDouble("MIN_LONGITUDE"); - double max_longitude = rs.getDouble("MAX_LONGITUDE"); - String device_identification = rs.getString("DEVICE_IDENTIFICATION"); - String device_name = rs.getString("NAME"); - String device_type = rs.getString("TYPE"); - String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP"); - long count = rs.getLong("COUNT"); - String geohashPrefix = rs.getString("GEOHASH_PREFIX"); + latitude = rs.getDouble("LATITUDE"); + longitude = rs.getDouble("LONGITUDE"); + minLatitude = rs.getDouble("MIN_LATITUDE"); + maxLatitude = rs.getDouble("MAX_LATITUDE"); + minLongitude = rs.getDouble("MIN_LONGITUDE"); + maxLongitude = rs.getDouble("MAX_LONGITUDE"); + count = rs.getLong("COUNT"); + geohashPrefix = rs.getString("GEOHASH_PREFIX"); + if (count == 1) { + device = DeviceManagementDAOUtil.loadDevice(rs); + } else { + device = null; + } geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), - new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude), - count, geohashPrefix, device_identification, device_name, device_type, last_seen)); + new GeoCoordinate(minLatitude, minLongitude), new GeoCoordinate(maxLatitude, maxLongitude), + count, geohashPrefix, device)); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of " + + throw new DeviceManagementDAOException("Error occurred while retrieving information of " + "Geo Clusters", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 83615eb056..eb3fa87f54 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -67,6 +67,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; + try { Connection conn = getConnection(); @@ -87,10 +90,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DESCRIPTION, " + "d.NAME, " + "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + "t.NAME AS DEVICE_TYPE "; - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + if (serial != null) { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.ID= i.DEVICE_ID " + + "AND i.KEY_FIELD = 'serial' " + + "AND i.VALUE_FIELD = ? " + + "AND d.TENANT_ID = ? "; + isSerialProvided = true; + } else { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; + } //Add query for last updated timestamp if (since != null) { sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; @@ -128,6 +140,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; + if (isSerialProvided) { + stmt.setString(paramIdx++, serial); + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -877,11 +892,15 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getSubscribedDevices(int offsetValue, int limitValue, - List deviceIds, int tenantId, List status) + public List getSubscribedDevices(PaginationRequest request, List deviceIds, int tenantId) throws DeviceManagementDAOException { Connection conn; - + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + List status = request.getStatusList(); + String name = request.getDeviceName(); + String user = request.getOwner(); + String ownership = request.getOwnership(); try { List devices = new ArrayList<>(); if (deviceIds.isEmpty()) { @@ -891,6 +910,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; boolean isStatusProvided = false; + boolean isDeviceNameProvided = false; + boolean isOwnerProvided = false; + boolean isOwnershipProvided = false; + StringJoiner joiner = new StringJoiner(",", "SELECT " + "DM_DEVICE.ID AS DEVICE_ID, " @@ -918,6 +941,18 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { deviceIds.stream().map(ignored -> "?").forEach(joiner::add); String query = joiner.toString(); + if (name != null && !name.isEmpty()) { + query += " AND DM_DEVICE.NAME LIKE ?"; + isDeviceNameProvided = true; + } + if (ownership != null && !ownership.isEmpty()) { + query += " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + if (user != null && !user.isEmpty()) { + query += " AND e.OWNER = ?"; + isOwnerProvided = true; + } if (status != null && !status.isEmpty()) { query += buildStatusQuery(status); isStatusProvided = true; @@ -930,8 +965,16 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { for (Integer deviceId : deviceIds) { ps.setObject(index++, deviceId); } - ps.setInt(index++, tenantId); + if (isDeviceNameProvided) { + ps.setString(index++, name + "%"); + } + if (isOwnershipProvided) { + ps.setString(index++, ownership); + } + if (isOwnerProvided) { + ps.setString(index++, user); + } if (isStatusProvided) { for (String deviceStatus : status) { ps.setString(index++, deviceStatus); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index ed5a8c843c..4393a4546e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -68,6 +68,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -88,9 +90,19 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DESCRIPTION, " + "d.NAME, " + "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "t.NAME AS DEVICE_TYPE "; + + if (serial != null) { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.ID= i.DEVICE_ID " + + "AND i.KEY_FIELD = 'serial' " + + "AND i.VALUE_FIELD = ? " + + "AND d.TENANT_ID = ? "; + isSerialProvided = true; + } else { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; + } //Add query for last updated timestamp if (since != null) { sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; @@ -128,6 +140,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; + if (isSerialProvided) { + stmt.setString(paramIdx++, serial); + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -847,11 +862,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getSubscribedDevices(int offsetValue, int limitValue, - List deviceIds, int tenantId, List status) + public List getSubscribedDevices(PaginationRequest request, List deviceIds, int tenantId) throws DeviceManagementDAOException { Connection conn; - + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + List status = request.getStatusList(); + String name = request.getDeviceName(); + String user = request.getOwner(); + String ownership = request.getOwnership(); try { List devices = new ArrayList<>(); if (deviceIds.isEmpty()) { @@ -861,6 +880,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; boolean isStatusProvided = false; + boolean isDeviceNameProvided = false; + boolean isOwnerProvided = false; + boolean isOwnershipProvided = false; StringJoiner joiner = new StringJoiner(",", "SELECT " + "DM_DEVICE.ID AS DEVICE_ID, " @@ -888,6 +910,18 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { deviceIds.stream().map(ignored -> "?").forEach(joiner::add); String query = joiner.toString(); + if (name != null && !name.isEmpty()) { + query += " AND DM_DEVICE.NAME LIKE ?"; + isDeviceNameProvided = true; + } + if (ownership != null && !ownership.isEmpty()) { + query += " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + if (user != null && !user.isEmpty()) { + query += " AND e.OWNER = ?"; + isOwnerProvided = true; + } if (status != null && !status.isEmpty()) { query += buildStatusQuery(status); isStatusProvided = true; @@ -902,6 +936,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } ps.setInt(index++, tenantId); + if (isDeviceNameProvided) { + ps.setString(index++, name + "%"); + } + if (isOwnershipProvided) { + ps.setString(index++, ownership); + } + if (isOwnerProvided) { + ps.setString(index++, user); + } if (isStatusProvided) { for (String deviceStatus : status) { ps.setString(index++, deviceStatus); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index cfefbb8b3f..66313603cb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -67,6 +67,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -87,11 +89,19 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DESCRIPTION, " + "d.NAME, " + "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.TENANT_ID = ?"; + "t.NAME AS DEVICE_TYPE "; + + if (serial != null) { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.ID= i.DEVICE_ID " + + "AND i.KEY_FIELD = 'serial' " + + "AND i.VALUE_FIELD = ? " + + "AND d.TENANT_ID = ? "; + isSerialProvided = true; + } else { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; + } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -124,6 +134,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; + if (isSerialProvided) { + stmt.setString(paramIdx++, serial); + } stmt.setInt(paramIdx++, tenantId); if (isDeviceTypeProvided) { stmt.setString(paramIdx++, deviceType); @@ -827,11 +840,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getSubscribedDevices(int offsetValue, int limitValue, - List deviceIds, int tenantId, List status) + public List getSubscribedDevices(PaginationRequest request, List deviceIds, int tenantId) throws DeviceManagementDAOException { Connection conn; - + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + List status = request.getStatusList(); + String name = request.getDeviceName(); + String user = request.getOwner(); + String ownership = request.getOwnership(); try { List devices = new ArrayList<>(); if (deviceIds.isEmpty()) { @@ -841,6 +858,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; boolean isStatusProvided = false; + boolean isDeviceNameProvided = false; + boolean isOwnerProvided = false; + boolean isOwnershipProvided = false; StringJoiner joiner = new StringJoiner(",", "SELECT " + "DM_DEVICE.ID AS DEVICE_ID, " @@ -868,6 +888,18 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { deviceIds.stream().map(ignored -> "?").forEach(joiner::add); String query = joiner.toString(); + if (name != null && !name.isEmpty()) { + query += " AND DM_DEVICE.NAME LIKE ?"; + isDeviceNameProvided = true; + } + if (ownership != null && !ownership.isEmpty()) { + query += " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + if (user != null && !user.isEmpty()) { + query += " AND e.OWNER = ?"; + isOwnerProvided = true; + } if (status != null && !status.isEmpty()) { query += buildStatusQuery(status); isStatusProvided = true; @@ -882,6 +914,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } ps.setInt(index++, tenantId); + if (isDeviceNameProvided) { + ps.setString(index++, name + "%"); + } + if (isOwnershipProvided) { + ps.setString(index++, ownership); + } + if (isOwnerProvided) { + ps.setString(index++, user); + } if (isStatusProvided) { for (String deviceStatus : status) { ps.setString(index++, deviceStatus); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 755f882a46..8911beca49 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.dao.impl.device; -import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Count; @@ -29,8 +28,8 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import java.sql.Connection; @@ -69,6 +68,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; + String serial = request.getSerialNumber(); + boolean isSerialProvided = false; try { conn = getConnection(); @@ -89,8 +90,19 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DESCRIPTION, " + "d.NAME, " + "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "t.NAME AS DEVICE_TYPE "; + + if (serial != null) { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.ID= i.DEVICE_ID " + + "AND i.KEY_FIELD = 'serial' " + + "AND i.VALUE_FIELD = ? " + + "AND d.TENANT_ID = ? "; + isSerialProvided = true; + } else { + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? "; + } //Add query for last updated timestamp if (since != null) { sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; @@ -128,6 +140,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; + if (isSerialProvided) { + stmt.setString(paramIdx++, serial); + } stmt.setInt(paramIdx++, tenantId); if (isSinceProvided) { stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); @@ -693,11 +708,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getSubscribedDevices(int offsetValue, int limitValue, - List deviceIds, int tenantId, List status) + public List getSubscribedDevices(PaginationRequest request, List deviceIds, int tenantId) throws DeviceManagementDAOException { Connection conn; - + int limitValue = request.getRowCount(); + int offsetValue = request.getStartIndex(); + List status = request.getStatusList(); + String name = request.getDeviceName(); + String user = request.getOwner(); + String ownership = request.getOwnership(); try { List devices = new ArrayList<>(); if (deviceIds.isEmpty()) { @@ -707,6 +726,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; boolean isStatusProvided = false; + boolean isDeviceNameProvided = false; + boolean isOwnerProvided = false; + boolean isOwnershipProvided = false; StringJoiner joiner = new StringJoiner(",", "SELECT " + "DM_DEVICE.ID AS DEVICE_ID, " @@ -734,6 +756,18 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { deviceIds.stream().map(ignored -> "?").forEach(joiner::add); String query = joiner.toString(); + if (name != null && !name.isEmpty()) { + query += " AND DM_DEVICE.NAME LIKE ?"; + isDeviceNameProvided = true; + } + if (ownership != null && !ownership.isEmpty()) { + query += " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + if (user != null && !user.isEmpty()) { + query += " AND e.OWNER = ?"; + isOwnerProvided = true; + } if (status != null && !status.isEmpty()) { query += buildStatusQuery(status); isStatusProvided = true; @@ -748,6 +782,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } ps.setInt(index++, tenantId); + if (isDeviceNameProvided) { + ps.setString(index++, name + "%"); + } + if (isOwnershipProvided) { + ps.setString(index++, ownership); + } + if (isOwnerProvided) { + ps.setString(index++, user); + } if (isStatusProvided) { for (String deviceStatus : status) { ps.setString(index++, deviceStatus); @@ -1089,6 +1132,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //TODO: Override for MSSQL + /* @Override public List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, int geohashLength, int tenantId) throws DeviceManagementDAOException { @@ -1163,4 +1208,5 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } return geoClusters; } + */ } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index b152e65a84..e1ce6c4f9c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -22,22 +22,17 @@ 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.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; -import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceDetailsWrapper; +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.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.EventPublishingException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; -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.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; @@ -46,18 +41,14 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; - -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; -import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; @@ -178,9 +169,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { deviceInfo.getAvailableRAMMemory(), deviceInfo.isPluggedIn() }; - DeviceManagerUtil.getEventPublisherService().publishEvent( - DEVICE_INFO_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload - ); + //todo:amalka +// DeviceManagerUtil.getEventPublisherService().publishEvent( +// DEVICE_INFO_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload +// ); } } catch (TransactionManagementException e) { throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e); @@ -193,8 +185,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " + "device", e); - } catch (DataPublisherConfigurationException e) { - throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); + //todo:amalka +// } catch (DataPublisherConfigurationException e) { +// throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -389,9 +382,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { deviceLocation.getBearing(), deviceLocation.getDistance() }; - DeviceManagerUtil.getEventPublisherService().publishEvent( - LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload - ); + //todo:amalka +// DeviceManagerUtil.getEventPublisherService().publishEvent( +// LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload +// ); } DeviceManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { @@ -403,9 +397,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } catch (DeviceManagementException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while getting the device information.", e); - } catch (DataPublisherConfigurationException e) { - DeviceManagementDAOFactory.rollbackTransaction(); - throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); + //todo:amalka +// } catch (DataPublisherConfigurationException e) { +// DeviceManagementDAOFactory.rollbackTransaction(); +// throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); } finally { DeviceManagementDAOFactory.closeConnection(); } 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 bc132a9b20..c7eb730c4e 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 @@ -22,6 +22,10 @@ public class CommandOperation extends Operation { private boolean enabled; + public CommandOperation() { + setControl(Control.NO_REPEAT); + } + public boolean isEnabled() { return enabled; } @@ -34,8 +38,4 @@ 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 c2be65a372..28116d5dc6 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 @@ -23,10 +23,11 @@ import java.util.List; public class ConfigOperation extends Operation { - private List properties; + private final List properties; public ConfigOperation() { - properties = new ArrayList(); + properties = new ArrayList<>(); + setControl(Control.REPEAT); } public List getConfigProperties() { @@ -37,6 +38,10 @@ public class ConfigOperation extends Operation { properties.add(new Property(name, value, type)); } + public Type getType() { + return Type.CONFIG; + } + public static class Property { private String name; private Object value; @@ -73,13 +78,4 @@ public class ConfigOperation extends Operation { } } - public Type getType() { - 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/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 dc6ae4dd78..bc93bcf0f8 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 @@ -19,7 +19,13 @@ package org.wso2.carbon.device.mgt.core.dto.operation.mgt; import java.util.List; -public class PolicyOperation extends Operation{ +public class PolicyOperation extends Operation { + + private List profileOperations; + + public PolicyOperation() { + setControl(Control.REPEAT); + } public List getProfileOperations() { return profileOperations; @@ -29,10 +35,4 @@ public class PolicyOperation extends Operation{ this.profileOperations = profileOperations; } - 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 107cf091d7..9e3db16f2e 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 @@ -22,13 +22,12 @@ import java.io.Serializable; public class ProfileOperation extends ConfigOperation implements Serializable { + public ProfileOperation() { + super(); + } + public Type getType() { 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/geo/GeoCluster.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java deleted file mode 100644 index e4838aaf6e..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/GeoCluster.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.wso2.carbon.device.mgt.core.geo; - -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; - -public class GeoCluster { - private GeoCoordinate coordinates; - private GeoCoordinate southWestBound; - private GeoCoordinate northEastBound; - private long count; - private String geohashPrefix; - private String deviceIdentification; - private String deviceName; - private String deviceType; - private String lastSeen; - - - public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound, long count, - String geohashPrefix, String deviceIdentification, String deviceName, String deviceType, String lastSeen){ - this.coordinates=coordinates; - this.southWestBound=southWestBound; - this.northEastBound=northEastBound; - this.count=count; - this.geohashPrefix=geohashPrefix; - this.deviceIdentification=deviceIdentification; - this.deviceName=deviceName; - this.deviceType=deviceType; - this.lastSeen = lastSeen; - - } - - public String getGeohashPrefix() { - return geohashPrefix; - } - - public long getCount() { - return count; - } - - public GeoCoordinate getCoordinates() { - return coordinates; - } - - public GeoCoordinate getSouthWestBound() { - return southWestBound; - } - - public GeoCoordinate getNorthEastBound() { - return northEastBound; - } - - public String getDeviceIdentification() { - return deviceIdentification; - } - - public String getDeviceName() { - return deviceName; - } - - public String getDeviceType() { return deviceType; - } - - public String getLastSeen() { - return lastSeen; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoCoordinate.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoCoordinate.java deleted file mode 100644 index 45ca28f0d4..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoCoordinate.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.wso2.carbon.device.mgt.core.geo.geoHash; - - - -public class GeoCoordinate { - private double latitude; - private double longitude; - - public GeoCoordinate(double latitude, double longitude){ - this.latitude=latitude; - this.longitude=longitude; - } - - public double getLatitude() { - return latitude; - } - - public double getLongitude() { - return longitude; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoHashGenerator.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoHashGenerator.java index 21d3ac85e9..557e4ebfe9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoHashGenerator.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/GeoHashGenerator.java @@ -1,15 +1,33 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.core.geo.geoHash; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; - -import java.util.HashMap; -import java.util.Map; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; public class GeoHashGenerator { + private static final String BASE_32 = "0123456789bcdefghjkmnpqrstuvwxyz"; private static final int GEOHASH_LENGTH = 16; - private GeoHashGenerator(){}; + private GeoHashGenerator() { + } private static int divideRangeByValue(double value, double[] range) { double mid = middle(range); @@ -36,7 +54,6 @@ public class GeoHashGenerator { } public static String encodeGeohash(double latitude, double longitude) { - int geohashLength=GEOHASH_LENGTH; double[] latRange = new double[]{-90.0, 90.0}; double[] lonRange = new double[]{-180.0, 180.0}; boolean isEven = true; @@ -44,7 +61,7 @@ public class GeoHashGenerator { int base32CharIndex = 0; StringBuilder geohash = new StringBuilder(); - while (geohash.length() < geohashLength) { + while (geohash.length() < GEOHASH_LENGTH) { if (isEven) { base32CharIndex = (base32CharIndex << 1) | divideRangeByValue(longitude, lonRange); } else { @@ -85,8 +102,7 @@ public class GeoHashGenerator { isEvenBit = !isEvenBit; } } - GeoCoordinate coordinates = new GeoCoordinate(middle(latRange),middle(lonRange)); - return coordinates; + return new GeoCoordinate(middle(latRange), middle(lonRange)); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/GeoHashLengthStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/GeoHashLengthStrategy.java index f6845b305e..99032ee211 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/GeoHashLengthStrategy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/GeoHashLengthStrategy.java @@ -1,11 +1,31 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.core.geo.geoHash.geoHashStrategy; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; /** * This interface is to decide a length for the geohash prefix * which will be used to group the clusters based on geohash */ public interface GeoHashLengthStrategy { + int getGeohashLength(GeoCoordinate southWest, GeoCoordinate northEast, int zoom); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/ZoomGeoHashLengthStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/ZoomGeoHashLengthStrategy.java index 0dd0e762f9..1eddf90602 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/ZoomGeoHashLengthStrategy.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/geoHash/geoHashStrategy/ZoomGeoHashLengthStrategy.java @@ -1,11 +1,31 @@ +/* + * Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.core.geo.geoHash.geoHashStrategy; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; -/**A class that will decide the geoHashLength based on the zoom level and -* the boundaries of the map**/ +/** + * A class that will decide the geoHashLength based on the zoom level and + * the boundaries of the map + **/ -public class ZoomGeoHashLengthStrategy implements GeoHashLengthStrategy{ +public class ZoomGeoHashLengthStrategy implements GeoHashLengthStrategy { private int minGeohashLength = 1; private int maxGeohashLength = 16; @@ -19,35 +39,36 @@ public class ZoomGeoHashLengthStrategy implements GeoHashLengthStrategy{ return (int) Math.max(minGeohashLength, Math.min(a * Math.exp(b * zoom), maxGeohashLength)); } - public void setMinGeohashLength(int minGeohashLength) { - this.minGeohashLength = minGeohashLength; - } - - public void setMaxGeohashLength(int maxGeohashLength) { - this.maxGeohashLength = maxGeohashLength; - } - - public void setMinZoom(int minZoom) { - this.minZoom = minZoom; - } - - public void setMaxZoom(int maxZoom) { - this.maxZoom = maxZoom; - } - public int getMinGeohashLength() { return minGeohashLength; } + public void setMinGeohashLength(int minGeohashLength) { + this.minGeohashLength = minGeohashLength; + } + public int getMaxGeohashLength() { return maxGeohashLength; } + public void setMaxGeohashLength(int maxGeohashLength) { + this.maxGeohashLength = maxGeohashLength; + } + public int getMinZoom() { return minZoom; } + public void setMinZoom(int minZoom) { + this.minZoom = minZoom; + } + public int getMaxZoom() { return maxZoom; } + + public void setMaxZoom(int maxZoom) { + this.maxZoom = maxZoom; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java index 9c77c75588..fad3138d44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java @@ -44,11 +44,11 @@ import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationExceptio import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.geo.service.Alert; +import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; import org.wso2.carbon.device.mgt.common.geo.service.GeoFenceEventMeta; -import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; -import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; import org.wso2.carbon.device.mgt.core.cache.impl.GeoCacheManagerImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; @@ -85,11 +85,11 @@ import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Collections; import java.util.Set; import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices.DAS_PORT; @@ -101,7 +101,7 @@ import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoSer */ public class GeoLocationProviderServiceImpl implements GeoLocationProviderService { - private static Log log = LogFactory.getLog(GeoLocationProviderServiceImpl.class); + private static final Log log = LogFactory.getLog(GeoLocationProviderServiceImpl.class); /** * required soap header for authorization @@ -136,6 +136,18 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic this.geofenceDAO = DeviceManagementDAOFactory.getGeofenceDAO(); } + public static JWTClientManagerService getJWTClientManagerService() { + JWTClientManagerService jwtClientManagerService; + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + jwtClientManagerService = (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "jwtClientManagerServicehas not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } + @Override public List getWithinAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { @@ -227,7 +239,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic return fences; } catch (RegistryException | IOException e) { throw new GeoLocationBasedServiceException( - "Error occurred while getting the geo alerts" , e); + "Error occurred while getting the geo alerts", e); } } @@ -334,7 +346,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic @Override public boolean createGeoAlert(Alert alert, String alertType) - throws GeoLocationBasedServiceException,AlertAlreadyExistException { + throws GeoLocationBasedServiceException, AlertAlreadyExistException { return saveGeoAlert(alert, alertType, false); } @@ -346,12 +358,12 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic @Override public boolean updateGeoAlert(Alert alert, String alertType) - throws GeoLocationBasedServiceException,AlertAlreadyExistException { + throws GeoLocationBasedServiceException, AlertAlreadyExistException { return saveGeoAlert(alert, alertType, true); } private boolean saveGeoAlert(Alert alert, String alertType, boolean isUpdate) - throws GeoLocationBasedServiceException,AlertAlreadyExistException { + throws GeoLocationBasedServiceException, AlertAlreadyExistException { Type type = new TypeToken>() { }.getType(); @@ -408,7 +420,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic if (validationResponse.equals("success")) { allActiveExecutionPlanConfigs = eventprocessorStub.getAllActiveExecutionPlanConfigurations(); if (isUpdate) { - for (ExecutionPlanConfigurationDto activeExectionPlanConfig:allActiveExecutionPlanConfigs) { + for (ExecutionPlanConfigurationDto activeExectionPlanConfig : allActiveExecutionPlanConfigs) { activeExecutionPlan = activeExectionPlanConfig.getExecutionPlan(); if (activeExecutionPlan.contains(executionPlanName)) { eventprocessorStub.editActiveExecutionPlan(parsedTemplate, executionPlanName); @@ -417,14 +429,14 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } eventprocessorStub.deployExecutionPlan(parsedTemplate); } else { - for (ExecutionPlanConfigurationDto activeExectionPlanConfig:allActiveExecutionPlanConfigs) { + for (ExecutionPlanConfigurationDto activeExectionPlanConfig : allActiveExecutionPlanConfigs) { activeExecutionPlan = activeExectionPlanConfig.getExecutionPlan(); if (activeExecutionPlan.contains(executionPlanName)) { throw new AlertAlreadyExistException("Execution plan already exists with name " + executionPlanName); } } - updateRegistry(getRegistryPath(alertType, alert.getQueryName()),content,options); + updateRegistry(getRegistryPath(alertType, alert.getQueryName()), content, options); eventprocessorStub.deployExecutionPlan(parsedTemplate); } } else { @@ -519,7 +531,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic if (validationResponse.equals("success")) { allActiveExecutionPlanConfigs = eventprocessorStub.getAllActiveExecutionPlanConfigurations(); if (isUpdate) { - for (ExecutionPlanConfigurationDto activeExectionPlanConfig:allActiveExecutionPlanConfigs) { + for (ExecutionPlanConfigurationDto activeExectionPlanConfig : allActiveExecutionPlanConfigs) { activeExecutionPlan = activeExectionPlanConfig.getExecutionPlan(); if (activeExecutionPlan.contains(executionPlanName)) { eventprocessorStub.editActiveExecutionPlan(parsedTemplate, executionPlanName); @@ -528,7 +540,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } eventprocessorStub.deployExecutionPlan(parsedTemplate); } else { - for (ExecutionPlanConfigurationDto activeExectionPlanConfig:allActiveExecutionPlanConfigs) { + for (ExecutionPlanConfigurationDto activeExectionPlanConfig : allActiveExecutionPlanConfigs) { activeExecutionPlan = activeExectionPlanConfig.getExecutionPlan(); if (activeExecutionPlan.contains(executionPlanName)) { throw new AlertAlreadyExistException("Execution plan already exists with name " @@ -605,32 +617,32 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } private String getRegistryPath(String alertType, String queryName) - throws GeoLocationBasedServiceException { - String path = ""; - if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_WITHIN + - "/" + "/" + queryName; - } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_EXIT + - "/" + queryName; - } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_SPEED + - "/" ; - } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_PROXIMITY + - "/" + queryName; - } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_STATIONARY + - "/" + queryName; - } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { - path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_TRAFFIC + - "/" + queryName; - } else { - throw new GeoLocationBasedServiceException( - "Unrecognized execution plan type: " + alertType); - } - return path; + throws GeoLocationBasedServiceException { + String path = ""; + if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_WITHIN + + "/" + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_EXIT + + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_SPEED + + "/"; + } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_PROXIMITY + + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_STATIONARY + + "/" + queryName; + } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { + path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_TRAFFIC + + "/" + queryName; + } else { + throw new GeoLocationBasedServiceException( + "Unrecognized execution plan type: " + alertType); } + return path; + } private String getExecutionPlanName(String alertType, String queryName, String deviceId, String owner) { if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { @@ -798,7 +810,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic InputStream inputStream = resource.getContentStream(); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); - return "{'speedLimit':" + writer.toString() + "}"; + return "{'speedLimit':" + writer + "}"; } catch (RegistryException | IOException e) { return "{'content': false}"; } @@ -816,7 +828,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic InputStream inputStream = resource.getContentStream(); StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); - return "{'speedLimit':" + writer.toString() + "}"; + return "{'speedLimit':" + writer + "}"; } catch (RegistryException | IOException e) { return "{'content': false}"; } @@ -835,8 +847,8 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic List proxTimeObj = (List) props.get(GeoServices.PROXIMITY_TIME); return String.format("{proximityDistance:\"%s\", proximityTime:\"%s\"}", - proxDisObj != null ? proxDisObj.get(0).toString() : "", - proxTimeObj != null ? proxTimeObj.get(0).toString() : ""); + proxDisObj != null ? proxDisObj.get(0).toString() : "", + proxTimeObj != null ? proxTimeObj.get(0).toString() : ""); } else { return "{'content': false}"; } @@ -868,7 +880,6 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } } - @Override public List getStationaryAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { @@ -1079,7 +1090,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } private String parseTemplate(String alertType, Map parseMap) throws - GeoLocationBasedServiceException { + GeoLocationBasedServiceException { String templatePath = "alerts/Geo-ExecutionPlan-" + alertType + "_alert.siddhiql"; InputStream resource = getClass().getClassLoader().getResourceAsStream(templatePath); if (resource == null) { @@ -1142,22 +1153,22 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } private void updateRegistry(String path, Object content, Map options) - throws GeoLocationBasedServiceException { - try { + throws GeoLocationBasedServiceException { + try { - Registry registry = getGovernanceRegistry(); - Resource newResource = registry.newResource(); - newResource.setContent(content); - newResource.setMediaType("application/json"); - for (Map.Entry option : options.entrySet()) { - newResource.addProperty(option.getKey(), option.getValue()); - } - registry.put(path, newResource); - } catch (RegistryException e) { - throw new GeoLocationBasedServiceException( - "Error occurred while setting the Within Alert", e); + Registry registry = getGovernanceRegistry(); + Resource newResource = registry.newResource(); + newResource.setContent(content); + newResource.setMediaType("application/json"); + for (Map.Entry option : options.entrySet()) { + newResource.addProperty(option.getKey(), option.getValue()); } + registry.put(path, newResource); + } catch (RegistryException e) { + throw new GeoLocationBasedServiceException( + "Error occurred while setting the Within Alert", e); } + } /** * Loads the keystore. @@ -1207,7 +1218,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic */ private SSLContext initSSLConnection(String tenantAdminUser) throws NoSuchAlgorithmException, UnrecoverableKeyException, - KeyStoreException, KeyManagementException, IOException, CertificateException { + KeyStoreException, KeyManagementException, IOException, CertificateException { String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( "Security.TrustStore.Password"); @@ -1243,18 +1254,6 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } } - public static JWTClientManagerService getJWTClientManagerService() { - JWTClientManagerService jwtClientManagerService; - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - jwtClientManagerService = (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); - if (jwtClientManagerService == null) { - String msg = "jwtClientManagerServicehas not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return jwtClientManagerService; - } - @Override public boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException, EventConfigurationException { int tenantId; @@ -1291,7 +1290,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic List createdEventIds; try { setEventSource(geofenceData.getEventConfig()); - eventConfigService = DeviceManagementDataHolder.getInstance().getEventConfigurationService(); + eventConfigService = DeviceManagementDataHolder.getInstance().getEventConfigurationService(); createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds()); DeviceManagementDAOFactory.beginTransaction(); geofenceDAO.createGeofenceEventMapping(geofenceData.getId(), createdEventIds); @@ -1333,6 +1332,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic /** * Set source of the event to GEOFENCE + * * @param eventConfig event list to be set event source */ private void setEventSource(List eventConfig) { @@ -1365,7 +1365,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } return geofence; } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while retrieving Geofence data with ID "+fenceId; + String msg = "Error occurred while retrieving Geofence data with ID " + fenceId; log.error(msg, e); throw new GeoLocationBasedServiceException(msg, e); } catch (SQLException e) { @@ -1608,7 +1608,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic try { tenantId = DeviceManagementDAOUtil.getTenantId(); setEventSource(geofenceData.getEventConfig()); - eventConfigService = DeviceManagementDataHolder.getInstance().getEventConfigurationService(); + eventConfigService = DeviceManagementDataHolder.getInstance().getEventConfigurationService(); if (eventConfigService == null) { String msg = "Failed to load EventConfigurationProviderService osgi service of tenant " + tenantId; log.error(msg); @@ -1747,8 +1747,9 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic /** * Delete events of geofence + * * @param geofenceData geofence mapped with deleting events - * @param eventList events to be deleted + * @param eventList events to be deleted */ private void deleteGeoFenceEvents(GeofenceData geofenceData, List eventList) throws GeoLocationBasedServiceException { @@ -1762,7 +1763,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } try { - EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder + EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder .getInstance().getEventConfigurationService(); eventConfigService.deleteEvents(eventList); eventConfigService.createEventOperationTask(OperationMgtConstants.OperationCodes.EVENT_REVOKE, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventCreateCallback.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventCreateCallback.java index a5277e09a8..02c49b7406 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventCreateCallback.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventCreateCallback.java @@ -17,6 +17,7 @@ */ package org.wso2.carbon.device.mgt.core.geo.task; + public interface EventCreateCallback { void onCompleteEventOperation(Object values); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventOperationTaskException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventOperationTaskException.java index 4e8e14d914..3288410e76 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventOperationTaskException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/EventOperationTaskException.java @@ -18,7 +18,8 @@ package org.wso2.carbon.device.mgt.core.geo.task; -public class EventOperationTaskException extends Exception{ +public class EventOperationTaskException extends Exception { + public EventOperationTaskException(String message) { super(message); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/GeoFenceEventOperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/GeoFenceEventOperationManager.java index e18968524f..daea9d53df 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/GeoFenceEventOperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/task/GeoFenceEventOperationManager.java @@ -45,14 +45,15 @@ public class GeoFenceEventOperationManager { this.eventOperationCode = eventOperationCode; this.tenantId = tenantId; this.callback = callback; - isEventEnabled= DeviceConfigurationManager.getInstance().getDeviceManagementConfig() + isEventEnabled = DeviceConfigurationManager.getInstance().getDeviceManagementConfig() .getEventOperationTaskConfiguration().isEnabled(); } /** * Get executor for create EVENT_CONFIG / EVENT_REVOKE operations at the time of a device/s * assigned into a group or removed from a group - * @param groupId Id of the assigned / removed group + * + * @param groupId Id of the assigned / removed group * @param deviceIdentifiers Device identifiers assigned to / removed from the group * @return {@link GroupAssignmentEventOperationExecutor} Created executor to create operations */ @@ -72,7 +73,8 @@ public class GeoFenceEventOperationManager { /** * Get executor for create EVENT_CONFIG / EVENT_REVOKE operations at the time of a event is created - * @param groupIds list of group ids to apply the created event + * + * @param groupIds list of group ids to apply the created event * @param eventMetaData contains all the data of the related event * @return {@link EventOperationExecutor} The created event executor object */ 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 3a9ecefca3..618c05adf3 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 @@ -24,6 +24,10 @@ public class CommandOperation extends Operation { private boolean enabled; + public CommandOperation() { + setControl(Control.NO_REPEAT); + } + public boolean isEnabled() { return enabled; } @@ -35,8 +39,5 @@ 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 69d8aafc4a..753b170a1b 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 @@ -21,8 +21,6 @@ package org.wso2.carbon.device.mgt.core.operation.mgt; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; public class ConfigOperation extends Operation { @@ -38,6 +36,15 @@ public class ConfigOperation extends Operation { properties.add(new Property(name, value, type)); }*/ + public ConfigOperation() { + //properties = new ArrayList<>(); + setControl(Control.REPEAT); + } + + public Type getType() { + return Type.CONFIG; + } + public static class Property implements Serializable { private String name; private Object value; @@ -74,12 +81,4 @@ public class ConfigOperation extends Operation { } } - public Type getType() { - 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/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 6b36492a83..47ca55f95e 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 @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; + import java.util.List; public class PolicyOperation extends Operation { @@ -25,6 +26,10 @@ public class PolicyOperation extends Operation { public static final String POLICY_OPERATION_CODE = "POLICY_BUNDLE"; private List profileOperations; + public PolicyOperation() { + setControl(Control.REPEAT); + } + public List getProfileOperations() { return profileOperations; } @@ -33,8 +38,4 @@ 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 3423524666..ac1082317b 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 @@ -19,21 +19,21 @@ package org.wso2.carbon.device.mgt.core.operation.mgt; import java.io.Serializable; -import java.util.ArrayList; import java.util.List; public class ProfileOperation extends ConfigOperation implements Serializable { + private static final long serialVersionUID = -3322674908775087365L; private List correctiveActionIds; private List reactiveActionIds; - public Type getType() { - return Type.PROFILE; + public ProfileOperation() { + super(); } - public Control getControl(){ - return Control.REPEAT; + public Type getType() { + return Type.PROFILE; } public List getCorrectiveActionIds() { @@ -51,4 +51,5 @@ public class ProfileOperation extends ConfigOperation implements Serializable { public void setReactiveActionIds(List reactiveActionIds) { this.reactiveActionIds = reactiveActionIds; } + } 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 aed6c935a3..1ce3d8a006 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 @@ -53,8 +53,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.HashMap; -import java.util.Date; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -167,7 +165,7 @@ public class GenericOperationDAOImpl implements OperationDAO { try { Connection connection = OperationManagementDAOFactory.getConnection(); StringBuilder query = new StringBuilder("SELECT OPERATION_ID, ENROLMENT_ID FROM DM_ENROLMENT_OP_MAPPING " + - "WHERE OPERATION_CODE = ? AND STATUS = ? AND ENROLMENT_ID IN ("); + "WHERE OPERATION_CODE = ? AND STATUS IN ('NOTNOW', 'PENDING') AND ENROLMENT_ID IN ("); for (int i = 0; i < enrolmentIds.length; i++) { query.append(" ?,"); } @@ -175,10 +173,9 @@ public class GenericOperationDAOImpl implements OperationDAO { query.append(")"); stmt = connection.prepareStatement(query.toString()); stmt.setString(1, operationCode); - stmt.setString(2, Operation.Status.PENDING.toString()); for (int i = 0; i < enrolmentIds.length; i++) { - stmt.setInt(i + 3, enrolmentIds[i]); + stmt.setInt(i + 2, enrolmentIds[i]); } rs = stmt.executeQuery(); @@ -324,7 +321,7 @@ public class GenericOperationDAOImpl implements OperationDAO { for (int i = 0; i < operationResponseIds.size(); i++) { builder.append("?,"); } - sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ")"; + sql1 += builder.deleteCharAt(builder.length() - 1) + ")"; stmt = conn.prepareStatement(sql1); int i; for (i = 0; i < operationResponseIds.size(); i++) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index fb3dd19527..6ff661568c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -62,6 +62,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.UnauthorizedDeviceAccessException; import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; @@ -74,8 +75,8 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import java.sql.SQLException; import java.util.Date; @@ -827,8 +828,7 @@ public interface DeviceManagementProviderService { List getDeviceEnrolledTenants() throws DeviceManagementException; - List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength) throws DeviceManagementException; + List findGeoClusters(GeoQuery geoQuery) throws DeviceManagementException; int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException; @@ -905,14 +905,12 @@ public interface DeviceManagementProviderService { * This method retrieves a list of subscribed devices. * * @param devicesIds devices ids of the subscribed devices. - * @param offsetValue offset value for get paginated request. - * @param limitValue limit value for get paginated request. - * @param status status of the devices. + * @param request paginated request object. * @return {@link PaginationResult} * @throws DeviceManagementException if any service level or DAO level error occurs. */ - PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue, - List devicesIds, List status) throws DeviceManagementException; + PaginationResult getAppSubscribedDevices(PaginationRequest request, List devicesIds) + throws DeviceManagementException; /** * This method is used to get a list of applications installed in all enrolled devices 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 7456111973..5bf4162729 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 @@ -49,7 +49,6 @@ import org.apache.http.protocol.HTTP; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.common.ActivityPaginationRequest; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification; @@ -92,6 +91,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.exceptions.UnauthorizedDeviceAccessException; import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; +import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; @@ -128,8 +128,8 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; +import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; @@ -163,6 +163,8 @@ import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; +//import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; + public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -1964,20 +1966,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv operation.getStatus() != null ? operation.getStatus().toString() : null, operation.getOperationResponse() }; - DeviceManagerUtil.getEventPublisherService().publishEvent( - OPERATION_RESPONSE_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload - ); + //todo:amalka +// DeviceManagerUtil.getEventPublisherService().publishEvent( +// OPERATION_RESPONSE_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload +// ); } } } catch (DeviceManagementException e) { String msg = "Error occurred while reading configs."; log.error(msg, e); throw new OperationManagementException(msg, e); - } catch (DataPublisherConfigurationException e) { - String msg = "Error occurred while publishing event."; - log.error(msg, e); - throw new OperationManagementException(msg, e); - } + //todo:amalka + } //catch (DataPublisherConfigurationException e) { +// String msg = "Error occurred while publishing event."; +// log.error(msg, e); +// throw new OperationManagementException(msg, e); +// } } @Override @@ -2006,20 +2010,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv operation.getStatus() != null ? operation.getStatus().toString() : null, operation.getOperationResponse() }; - DeviceManagerUtil.getEventPublisherService().publishEvent( - OPERATION_RESPONSE_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload - ); + //todo:amalka +// DeviceManagerUtil.getEventPublisherService().publishEvent( +// OPERATION_RESPONSE_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload +// ); } } } catch (DeviceManagementException e) { String msg = "Error occurred while reading configs."; log.error(msg, e); throw new OperationManagementException(msg, e); - } catch (DataPublisherConfigurationException e) { - String msg = "Error occurred while publishing event."; - log.error(msg, e); - throw new OperationManagementException(msg, e); - } + //todo:amalka + } //catch (DataPublisherConfigurationException e) { +// String msg = "Error occurred while publishing event."; +// log.error(msg, e); +// throw new OperationManagementException(msg, e); +// } } @Override @@ -3371,18 +3377,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength) throws DeviceManagementException { + public List findGeoClusters(GeoQuery geoQuery) throws DeviceManagementException { if (log.isDebugEnabled()) { - if (deviceType == null || deviceType.isEmpty()) { - log.debug("get information about geo clusters."); - } else { - log.debug("get information about geo clusters for device type: " + deviceType); - } + log.debug("Get information about geo clusters for query: " + new Gson().toJson(geoQuery)); } try { DeviceManagementDAOFactory.openConnection(); - return deviceDAO.findGeoClusters(deviceType, southWest, northEast, geohashLength, this.getTenantId()); + return deviceDAO.findGeoClusters(geoQuery, this.getTenantId()); } catch (DeviceManagementDAOException e) { String msg = "Error occurred while retrieving the geo clusters."; log.error(msg, e); @@ -4156,9 +4157,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue, List devicesIds, - List status) throws DeviceManagementException { - + public PaginationResult getAppSubscribedDevices(PaginationRequest request, List devicesIds) throws DeviceManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (log.isDebugEnabled()) { log.debug("Getting all devices details for device ids: " + devicesIds); @@ -4167,15 +4166,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List subscribedDeviceDetails; try { DeviceManagementDAOFactory.openConnection(); - subscribedDeviceDetails = deviceDAO - .getSubscribedDevices(offsetValue, limitValue, devicesIds, tenantId, status); + subscribedDeviceDetails = deviceDAO.getSubscribedDevices(request, devicesIds, tenantId); if (subscribedDeviceDetails.isEmpty()) { paginationResult.setData(new ArrayList<>()); paginationResult.setRecordsFiltered(0); paginationResult.setRecordsTotal(0); return paginationResult; } - int count = deviceDAO.getSubscribedDeviceCount(devicesIds, tenantId, status); + int count = deviceDAO.getSubscribedDeviceCount(devicesIds, tenantId, request.getStatusList()); paginationResult.setRecordsFiltered(count); paginationResult.setRecordsTotal(count); } catch (DeviceManagementDAOException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java index 7bc831c313..5182fc3651 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -52,6 +52,7 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { @Override public void setProperties(Map properties) { + super.setProperties(properties); deviceType = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE); deviceTypeId = Integer.parseInt(properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID)); String deviceStatusTaskConfigStr = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index 360325e9ab..0c6f77c15d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -39,28 +39,26 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DynamicTaskContext; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.StartupOperationConfig; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; -import org.wso2.carbon.ntask.core.Task; -import org.wso2.carbon.user.api.UserStoreException; import java.util.List; import java.util.Map; public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { - private static Log log = LogFactory.getLog(DeviceDetailsRetrieverTask.class); + private static final Log log = LogFactory.getLog(DeviceDetailsRetrieverTask.class); private String deviceType; private DeviceManagementProviderService deviceManagementProviderService; @Override public void setProperties(Map map) { + super.setProperties(map); deviceType = map.get("DEVICE_TYPE"); } @@ -122,7 +120,7 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { //pass the configurations also from here, monitoring tasks try { if (deviceManagementProviderService.isDeviceMonitoringEnabled(deviceType)) { - deviceTaskManager.addOperations(super.getTaskContext()); + deviceTaskManager.addOperations(getTaskContext()); } } catch (DeviceMgtTaskException e) { log.error("Error occurred while trying to add the operations to " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index ef11b3bda2..0bbb59d2bd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -26,12 +26,27 @@ import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.ntask.core.Task; +import java.util.Map; + public abstract class DynamicPartitionedScheduleTask implements Task { private static final Log log = LogFactory.getLog(DynamicPartitionedScheduleTask.class); private static DynamicTaskContext taskContext = null; + private Map properties; + + @Override + public void setProperties(Map properties) { + this.properties = properties; + } + + public String getProperty(String name) { + if (properties == null) { + return null; + } + return properties.get(name); + } @Override public final void init() { @@ -97,11 +112,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task { } public static boolean isDynamicTaskEligible(){ - if(taskContext != null && taskContext.isPartitioningEnabled()) { - return true; - } else { - return false; - } + return taskContext != null && taskContext.isPartitioningEnabled(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java index 56a1c498a0..fb8a5b9235 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java @@ -61,6 +61,8 @@ public abstract class RandomlyAssignedScheduleTask implements Task { log.error("Error refreshing Variables necessary for Randomly Assigned Scheduled Task. " + "Dynamic Tasks will not function.", e); } + } else { + qualifiedToExecuteTask = true; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 7822754208..0a2932e930 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -50,7 +50,6 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.caching.impl.CacheImpl; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; import org.wso2.carbon.device.mgt.common.AppRegistrationCredentials; import org.wso2.carbon.device.mgt.common.ApplicationRegistration; import org.wso2.carbon.device.mgt.common.ApplicationRegistrationException; @@ -67,11 +66,11 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; @@ -129,6 +128,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; +//import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; + public final class DeviceManagerUtil { private static final Log log = LogFactory.getLog(DeviceManagerUtil.class); @@ -595,17 +596,18 @@ public final class DeviceManagerUtil { return Caching.getCacheManagerFactory().getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER); } - public static EventsPublisherService getEventPublisherService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - EventsPublisherService eventsPublisherService = - (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); - if (eventsPublisherService == null) { - String msg = "Event Publisher service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return eventsPublisherService; - } + //todo:amalka +// public static EventsPublisherService getEventPublisherService() { +// PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); +// EventsPublisherService eventsPublisherService = +// (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); +// if (eventsPublisherService == null) { +// String msg = "Event Publisher service has not initialized."; +// log.error(msg); +// throw new IllegalStateException(msg); +// } +// return eventsPublisherService; +// } /** * Retrieve EventConfigurationProviderService osgi service component diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 43353e1468..3c17f25ec2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -178,15 +178,15 @@ javax.xml.stream, javax.xml.parsers;resolution:=optional, org.apache.commons.lang, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.w3c.dom, org.wso2.carbon.ndatasource.core, org.wso2.carbon.registry.core.service, org.wso2.carbon.utils.dbcreator, org.wso2.carbon.utils.multitenancy, org.wso2.carbon.device.mgt.core.service, - com.google.gson, - org.osgi.framework + com.google.gson org.wso2.carbon.device.mgt.extensions.pull.notification, org.wso2.carbon.device.mgt.extensions.pull.notification.* diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/OperationMetadata.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/OperationMetadata.java index 81a4139d8e..9fc9715f4d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/OperationMetadata.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/OperationMetadata.java @@ -58,6 +58,7 @@ import java.util.List; "method", "contentType", "permission", + "scope", "filterList" }) public class OperationMetadata { @@ -74,6 +75,9 @@ public class OperationMetadata { @XmlElement(name = "permission") private String permission; + @XmlElement(name = "scope") + private String scope; + @XmlElementWrapper(name = "filters") @XmlElement(name = "filter") private List filterList; @@ -110,6 +114,14 @@ public class OperationMetadata { this.permission = permission; } + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + public List getFilterList() { return filterList; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java index 1043628369..95c702041f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/feature/ConfigurationBasedFeatureManager.java @@ -63,6 +63,7 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { private static final String OPERATION_META = "operationMeta"; private static final String CONTENT_TYPE = "contentType"; private static final String PERMISSION = "permission"; + private static final String SCOPE = "scope"; private static final String ICON = "icon"; private static final String FILTERS = "filters"; private static final String PATH_PARAMS = "pathParams"; @@ -108,6 +109,9 @@ public class ConfigurationBasedFeatureManager implements FeatureManager { if (StringUtils.isNotEmpty(metadata.getPermission())) { operationMeta.put(PERMISSION, metadata.getPermission()); } + if (StringUtils.isNotEmpty(metadata.getScope())) { + operationMeta.put(SCOPE, metadata.getScope()); + } if (metadata.getFilterList() != null && metadata.getFilterList().size() > 0) { operationMeta.put(FILTERS, metadata.getFilterList()); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml index 402dedb384..cda668636f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml index b3bef7291a..981a5383b3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -61,8 +61,8 @@ IoT Server Impl Bundle org.wso2.carbon.device.mgt.url.printer.internal - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, org.apache.axis2.*;version="${axis2.osgi.version.range}", org.wso2.carbon.core, diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 2d489faa9e..0e362501db 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml @@ -36,11 +36,8 @@ org.wso2.carbon.device.mgt.core org.wso2.carbon.device.mgt.common org.wso2.carbon.device.mgt.extensions - org.wso2.carbon.device.mgt.ui org.wso2.carbon.device.mgt.api - org.wso2.carbon.device.mgt.analytics.data.publisher org.wso2.carbon.device.mgt.url.printer - org.wso2.carbon.device.mgt.analytics.wsproxy io.entgra.carbon.device.mgt.config.api diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml index 70cdb93216..2a660006e6 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt heartbeat-management - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -53,20 +53,14 @@ org.apache.axis2.*;version="${axis2.osgi.version.range}", org.apache.axiom.*; version="${axiom.osgi.version.range}", - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.utils.*, org.wso2.carbon.ndatasource.core, org.w3c.dom, - org.apache.velocity;version="${velocity.version}", - org.apache.velocity.app;version="${velocity.version}", - org.apache.velocity.context;version="${velocity.version}", - org.apache.velocity.exception;version="${velocity.version}", - org.apache.velocity.runtime.resource;version="${velocity.version}", - org.apache.velocity.runtime.resource.loader;version="${velocity.version}", org.apache.commons.io, org.apache.axis2.transport.mail, org.apache.commons.collections, @@ -149,10 +143,6 @@ org.apache.axis2.wso2 axis2 - - org.wso2.orbit.org.apache.velocity - velocity - commons-io.wso2 commons-io diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index 08477b29cb..dae6112b77 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml index ae46c74805..2a9d3b6c2f 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml @@ -22,13 +22,12 @@ org.wso2.carbon.devicemgt identity-extensions - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.oauth.extensions - 4.1.16-SNAPSHOT bundle WSO2 Carbon - OAuth Extensions http://wso2.org @@ -45,10 +44,6 @@ org.wso2.carbon org.wso2.carbon.user.core - - - org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.keymgt com.googlecode.json-simple.wso2 @@ -104,7 +99,7 @@ org.wso2.carbon.utils, org.wso2.carbon.context, org.wso2.carbon.identity.oauth.*;version="${carbon.identity.framework.version.range}", - org.wso2.carbon.apimgt.keymgt.*;version="${carbon.api.mgt.version.range}", + org.wso2.carbon.base, org.wso2.carbon.identity.application.authentication.framework.model;version="${carbon.identity.framework.version.range}", org.wso2.carbon.identity.base;version="${carbon.identity.framework.version.range}", diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java index 1153cb0561..92dd1ad814 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/AccessTokenGrantHandler.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.keymgt.ScopesIssuer; import org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant.oauth.validator.LocalOAuthValidator; import org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; @@ -57,11 +56,6 @@ public class AccessTokenGrantHandler extends AbstractAuthorizationGrantHandler { } } - @Override - public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) { - return ScopesIssuer.getInstance().setScopes(tokReqMsgCtx); - } - @Override public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { if (!super.validateGrant(tokReqMsgCtx)) { diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedJWTGrantHandler.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedJWTGrantHandler.java index 006317f179..0fe613fa31 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedJWTGrantHandler.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedJWTGrantHandler.java @@ -20,14 +20,10 @@ package org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.keymgt.ScopesIssuer; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.grant.jwt.JWTBearerGrantHandler; import org.wso2.carbon.identity.oauth2.model.RequestParameter; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; /** * This sets up user with tenant aware username. @@ -37,11 +33,6 @@ public class ExtendedJWTGrantHandler extends JWTBearerGrantHandler { private static Log log = LogFactory.getLog(ExtendedJWTGrantHandler.class); private static final String TENANT_DOMAIN_KEY = "tenantDomain"; - @Override - public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) { - return ScopesIssuer.getInstance().setScopes(tokReqMsgCtx); - } - @Override public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedSAML2BearerGrantHandler.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedSAML2BearerGrantHandler.java index 5caededdaf..749cf84147 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedSAML2BearerGrantHandler.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/grant/ExtendedSAML2BearerGrantHandler.java @@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.oauth.extensions.handlers.grant; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.keymgt.ScopesIssuer; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; @@ -34,11 +33,6 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; public class ExtendedSAML2BearerGrantHandler extends SAML2BearerGrantHandler { private static Log log = LogFactory.getLog(ExtendedSAML2BearerGrantHandler.class); - @Override - public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) { - return ScopesIssuer.getInstance().setScopes(tokReqMsgCtx); - } - @Override public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { if(!super.validateGrant(tokReqMsgCtx)){ diff --git a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml index 4adb6539ab..33286cd1e6 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.authenticator.backend.oauth/pom.xml @@ -21,7 +21,7 @@ identity-extensions org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT 4.0.0 diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml index b793b016fa..dcabec21e4 100644 --- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt identity-extensions - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -185,8 +185,8 @@ org.wso2.carbon.identity.jwt.client.extension.* - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.wso2.carbon.context, org.wso2.carbon.registry.core, org.wso2.carbon.registry.core.exceptions, diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index e10007a1ac..05a00e3768 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml @@ -33,7 +33,6 @@ http://wso2.org - org.wso2.carbon.identity.authenticator.backend.oauth org.wso2.carbon.device.mgt.oauth.extensions org.wso2.carbon.identity.jwt.client.extension diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml index 4823875d18..6e0f87666d 100644 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt policy-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.complex.policy.decision.point - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Policy Decision Point WSO2 Carbon - Policy Decision Point diff --git a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml index 89a475e259..8c43b569f9 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml @@ -3,14 +3,13 @@ org.wso2.carbon.devicemgt policy-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.decision.point - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Policy Decision Point WSO2 Carbon - Policy Decision Point @@ -35,9 +34,9 @@ Policy Decision Point Bundle org.wso2.carbon.policy.decision.point.internal - org.wso2.carbon.context.*; - org.osgi.framework, - org.osgi.service.component, + org.wso2.carbon.context;version="${carbon.kernel.version.range}", + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, org.wso2.carbon.policy.mgt.common.*, org.wso2.carbon.policy.mgt.core.*, diff --git a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml index 91e54e19ae..00a3b9c925 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt policy-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -11,7 +11,6 @@ 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.information.point - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Policy Information Point WSO2 Carbon - Policy Information Point diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml index 7430fd3211..8aa6a91517 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt policy-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.policy.mgt.common - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Policy Management Common WSO2 Carbon - Policy Management Common diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml index 20aab933b0..2efdf89d5f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml @@ -22,13 +22,12 @@ org.wso2.carbon.devicemgt policy-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.policy.mgt.core - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Policy Management Core WSO2 Carbon - Policy Management Core @@ -53,8 +52,8 @@ Policy Management Core Bundle org.wso2.carbon.policy.mgt.core.internal - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.sql, javax.cache, diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java index b24e84f029..ba4cfd971c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -21,8 +21,8 @@ package org.wso2.carbon.policy.mgt.core.enforcement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -36,19 +36,13 @@ import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class DelegationTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(DelegationTask.class); - private PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance() + private final PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance() .getDeviceManagementConfig().getPolicyConfiguration(); - @Override - public void setProperties(Map map) { - - } - @Override public void executeDynamicTask() { try { @@ -70,10 +64,10 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { try { devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - if (super.isDynamicTaskEligible()) { + if (isDynamicTaskEligible()) { devices.addAll(service.getAllocatedDevices(deviceType, - super.getTaskContext().getActiveServerCount(), - super.getTaskContext().getServerHashIndex())); + getTaskContext().getActiveServerCount(), + getTaskContext().getServerHashIndex())); } else { devices.addAll(service.getAllDevices(deviceType, false)); } @@ -81,9 +75,9 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { if (device != null && device.getEnrolmentInfo() != null && device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { toBeNotified.add(device); - } - if (log.isDebugEnabled()) { - log.debug("Adding policy operation to device : " + device.getDeviceIdentifier()); + if (log.isDebugEnabled()) { + log.debug("Adding policy operation to device : " + device.getDeviceIdentifier()); + } } } if (!toBeNotified.isEmpty()) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index d51f283a8e..c93ff3d563 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -24,33 +24,22 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; import java.util.ArrayList; import java.util.List; -import java.util.Map; public class MonitoringTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(MonitoringTask.class); - @Override - public void setProperties(Map map) { - } - - @Override - public void executeDynamicTask() { - if (log.isDebugEnabled()) { - log.debug("Monitoring task started to run."); - } - this.executeforAllTenants(); - } + private String tenant; /** * Check whether Device platform (ex: android) is exist in the cdm-config.xml file before adding a @@ -66,30 +55,27 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { return policyMonitoringManager != null; } - private void executeforAllTenants() { - + @Override + public void executeDynamicTask() { + tenant = getProperty(PolicyManagementConstants.TENANT_ID); + if (tenant == null) { + log.warn("Tenant id of the Monitoring Task got null"); + return; + } + int tenantId = Integer.parseInt(tenant); if (log.isDebugEnabled()) { - log.debug("Monitoring task started to run for all tenants."); + log.debug("Monitoring task started to run for tenant: " + tenant); + } + if (MultitenantConstants.SUPER_TENANT_ID == tenantId) { + this.executeTask(); + return; } try { - DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder - .getInstance().getDeviceManagementService(); - List tenants = deviceManagementService.getDeviceEnrolledTenants(); - for (Integer tenant : tenants) { - if (MultitenantConstants.SUPER_TENANT_ID == tenant) { - this.executeTask(); - continue; - } - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenant, true); - this.executeTask(); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - } catch (DeviceManagementException e) { - log.error("Error occurred while trying to get the available tenants from device manager service ", e); + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); + this.executeTask(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } @@ -105,7 +91,7 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { } } } catch (PolicyComplianceException e) { - log.error("Error occurred while getting the device types."); + log.error("TID:[" + tenant + "] Error occurred while getting the device types."); } if (!deviceTypes.isEmpty()) { try { @@ -113,42 +99,42 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { PolicyManagementDataHolder.getInstance().getDeviceManagementService(); for (String deviceType : configDeviceTypes) { if (log.isDebugEnabled()) { - log.debug("Running task for device type : " + deviceType); + log.debug("TID:[" + tenant + "] Running task for device type : " + deviceType); } PolicyMonitoringManager monitoringService = PolicyManagementDataHolder.getInstance().getDeviceManagementService() .getPolicyMonitoringManager(deviceType); List devices; - if(super.isDynamicTaskEligible()){ - devices = deviceManagementProviderService.getAllocatedDevices(deviceType, - super.getTaskContext().getActiveServerCount(), - super.getTaskContext().getServerHashIndex()); + if(isDynamicTaskEligible()){ + devices = deviceManagementProviderService + .getAllocatedDevices(deviceType, getTaskContext().getActiveServerCount(), + getTaskContext().getServerHashIndex()); } else { devices = deviceManagementProviderService.getAllDevices(deviceType, false); } if (monitoringService != null && !devices.isEmpty()) { List notifiableDevices = new ArrayList<>(); if (log.isDebugEnabled()) { - log.debug("Removing inactive and blocked devices from the list for the device type : " + - deviceType); + log.debug("TID:[" + tenant + "] Removing inactive and blocked devices from " + + "the list for the device type : " + deviceType); } + StringBuilder sb = new StringBuilder(); for (Device device : devices) { EnrolmentInfo.Status status = device.getEnrolmentInfo().getStatus(); if (status.equals(EnrolmentInfo.Status.ACTIVE) || - status.equals(EnrolmentInfo.Status.INACTIVE) || status.equals(EnrolmentInfo.Status.UNREACHABLE)) { notifiableDevices.add(device); - } - if (log.isDebugEnabled()) { - log.debug("Adding monitoring operation to device : " + device.getDeviceIdentifier()); + if (log.isDebugEnabled()) { + if (sb.length() > 0) { + sb.append(", "); + } + sb.append(device.getDeviceIdentifier()); + } } } if (log.isDebugEnabled()) { - log.debug("Following '" + deviceType + "' devices selected to send the notification " + - "for policy monitoring"); - for (Device device : notifiableDevices) { - log.debug(device.getDeviceIdentifier()); - } + log.debug("TID:[" + tenant + "] Sending monitoring to '" + deviceType + + "' devices with ids [" + sb + "]"); } if (!notifiableDevices.isEmpty()) { monitoringManager.addMonitoringOperation(deviceType, notifiableDevices); @@ -156,13 +142,14 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { } } if (log.isDebugEnabled()) { - log.debug("Monitoring task running completed."); + log.debug("TID:[" + tenant + "] Monitoring task running completed."); } } catch (Exception e) { - log.error("Error occurred while trying to run a task.", e); + log.error("TID:[" + tenant + "] Error occurred while trying to run a task.", e); } } else { - log.info("No device types registered currently. So did not run the monitoring task."); + log.info("TID:[" + tenant + "] No device types registered currently. " + + "So did not run the monitoring task."); } } @@ -170,4 +157,5 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { protected void setup() { } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java index b4b358bc32..d6aefcee11 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -39,7 +39,7 @@ import java.util.Map; public class TaskScheduleServiceImpl implements TaskScheduleService { private static final Log log = LogFactory.getLog(TaskScheduleServiceImpl.class); - private PolicyConfiguration policyConfiguration; + private final PolicyConfiguration policyConfiguration; public TaskScheduleServiceImpl() { @@ -72,7 +72,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { Map properties = new HashMap<>(); properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); - String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + tenantId; if (!taskManager.isTaskScheduled(taskName)) { @@ -101,7 +101,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void stopTask() throws PolicyMonitoringTaskException { int tenantId = getTenantId(); try { - String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + tenantId; TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); if (taskService.isServerInit()) { TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); @@ -117,7 +117,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void updateTask(int monitoringFrequency) throws PolicyMonitoringTaskException { int tenantId = getTenantId(); try { - String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + tenantId; TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); @@ -129,7 +129,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { triggerInfo.setRepeatCount(-1); Map properties = new HashMap<>(); - properties.put("tenantId", String.valueOf(tenantId)); + properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, triggerInfo); @@ -150,7 +150,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { @Override public boolean isTaskScheduled() throws PolicyMonitoringTaskException { int tenantId = getTenantId(); - String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + tenantId; TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); TaskManager taskManager; try { diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index dd4d6e80c8..4f1db3f6ae 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,13 +23,12 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 policy-mgt - 4.1.16-SNAPSHOT pom WSO2 Carbon - Policy Management Component http://wso2.org @@ -39,7 +38,7 @@ org.wso2.carbon.policy.mgt.core org.wso2.carbon.policy.information.point org.wso2.carbon.policy.decision.point - org.wso2.carbon.complex.policy.decision.point + diff --git a/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml b/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml index 1888660a53..592564cc0a 100644 --- a/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/org.wso2.carbon.email.sender.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt email-sender - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -53,8 +53,8 @@ org.apache.axis2.*;version="${axis2.osgi.version.range}", org.apache.axiom.*; version="${axiom.osgi.version.range}", - org.osgi.framework, - org.osgi.service.component, + org.osgi.framework.*;version="${imp.package.version.osgi.framework}", + org.osgi.service.*;version="${imp.package.version.osgi.service}", org.apache.commons.logging, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context, diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index 61e795d747..da5fdb82a1 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index b307febc12..fc1c94aaef 100644 --- a/components/transport-mgt/pom.xml +++ b/components/transport-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml index d4f72461b4..c4bdb628f5 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -87,18 +87,13 @@ - org.apache.cxf - cxf-rt-frontend-jaxws + org.springframework + spring-web provided org.apache.cxf - cxf-rt-frontend-jaxrs - provided - - - org.apache.cxf - cxf-rt-transports-http + cxf-bundle-jaxrs provided diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/src/main/webapp/META-INF/webapp-classloading.xml index d0d7a01621..c0925583a3 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - CXF,Carbon + CXF3,Carbon diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml index 8edc2d7a44..ac4edf6955 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.common/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml index 49eae641ab..f88e557184 100644 --- a/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.core/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt sms-handler - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/pom.xml b/components/transport-mgt/sms-handler/pom.xml index 2f46ed8dfa..4c8815afc6 100644 --- a/components/transport-mgt/sms-handler/pom.xml +++ b/components/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml index d00ef252ad..0fcf6eee7d 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/pom.xml @@ -21,12 +21,11 @@ ui-request-interceptor io.entgra.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT 4.0.0 io.entgra.ui.request.interceptor - 4.1.16-SNAPSHOT war Entgra - Request Handling Proxy Servlet Proxy Service for Request Handling in Entgra EMM/IOT Server. @@ -99,18 +98,23 @@ - org.apache.cxf - cxf-rt-frontend-jaxws + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.application.extension + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.springframework + spring-web provided org.apache.cxf - cxf-rt-frontend-jaxrs - provided - - - org.apache.cxf - cxf-rt-transports-http + cxf-bundle-jaxrs provided diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java index 1079e78b27..7aaae1ca70 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java @@ -132,7 +132,7 @@ public class DefaultTokenHandler extends HttpServlet { URIBuilder ub = new URIBuilder(); ub.setScheme(HandlerConstants.WSS_PROTOCOL); ub.setHost(System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR)); - ub.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_CORE_PORT_ENV_VAR))); + ub.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_CORE_HTTPS_PORT_ENV_VAR))); ub.setPath(HandlerConstants.REMOTE_SESSION_CONTEXT); JsonObject responseJsonObj = new JsonObject(); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java index 49e0489de3..7bf0861f72 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/InvokerHandler.java @@ -73,6 +73,7 @@ public class InvokerHandler extends HttpServlet { private static final long serialVersionUID = -6508020875358160165L; private static AuthData authData; private static String apiEndpoint; + private static String iotsCoreUrl; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { @@ -368,8 +369,14 @@ public class InvokerHandler extends HttpServlet { if (log.isDebugEnabled()) { log.debug("refreshing the token"); } + String iotsCorePort = System.getProperty("iot.core.https.port"); + if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) { + iotsCorePort = System.getProperty("iot.core.http.port"); + } + iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host") + + HandlerConstants.COLON + iotsCorePort; HttpPost tokenEndpoint = new HttpPost( - apiEndpoint + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT); + iotsCoreUrl + HandlerConstants.TOKEN_ENDPOINT); HttpSession session = req.getSession(false); if (session == null) { log.error("Couldn't find a session, hence it is required to login and proceed."); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java index 133681355b..b1e34a99da 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/LoginHandler.java @@ -24,6 +24,9 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import io.entgra.ui.request.interceptor.beans.AuthData; +import io.entgra.ui.request.interceptor.cache.LoginCacheManager; +import io.entgra.ui.request.interceptor.cache.OAuthApp; +import io.entgra.ui.request.interceptor.cache.OAuthAppCacheKey; import io.entgra.ui.request.interceptor.exceptions.LoginException; import io.entgra.ui.request.interceptor.util.HandlerConstants; import io.entgra.ui.request.interceptor.util.HandlerUtil; @@ -36,6 +39,7 @@ import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HTTP; import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import org.json.JSONString; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -56,6 +60,7 @@ public class LoginHandler extends HttpServlet { private static String password; private static String gatewayUrl; private static String uiConfigUrl; + private static String iotsCoreUrl; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { @@ -66,34 +71,70 @@ public class LoginHandler extends HttpServlet { httpSession.invalidate(); } httpSession = req.getSession(true); - //setting session to expiry in 5 minutes - httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT)); JsonObject uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + int sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); - HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() - .encodeToString((username + HandlerConstants.COLON + password).getBytes())); - apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, HandlerConstants.PUBLISHER_APPLICATION_NAME, username, password)); + //setting session to expire in 1h + httpSession.setMaxInactiveInterval(sessionTimeOut); - ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); + // Check if OAuth app cache exists. If not create a new application. + LoginCacheManager loginCacheManager = new LoginCacheManager(); + loginCacheManager.initializeCacheManager(); + OAuthAppCacheKey oAuthAppCacheKey = new OAuthAppCacheKey(HandlerConstants.PUBLISHER_APPLICATION_NAME, username); + OAuthApp oAuthApp = loginCacheManager.getOAuthAppCache(oAuthAppCacheKey); - if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, clientAppResponse); - return; + if (oAuthApp == null) { + HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); + apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() + .encodeToString((username + HandlerConstants.COLON + password).getBytes())); + apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); + apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, HandlerConstants.PUBLISHER_APPLICATION_NAME, username, password)); + + ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); + + if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { + HandlerUtil.handleError(resp, clientAppResponse); + return; + } + + if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { + JsonParser jsonParser = new JsonParser(); + JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); + String clientId = null; + String clientSecret = null; + String encodedClientApp = null; + if (jClientAppResult.isJsonObject()) { + JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); + clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); + clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); + encodedClientApp = Base64.getEncoder() + .encodeToString((clientId + HandlerConstants.COLON + clientSecret).getBytes()); + + oAuthAppCacheKey = new OAuthAppCacheKey(HandlerConstants.PUBLISHER_APPLICATION_NAME, username); + oAuthApp = new OAuthApp( + HandlerConstants.PUBLISHER_APPLICATION_NAME, + username, + clientId, + clientSecret, + encodedClientApp + ); + loginCacheManager.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); + } + + if (getTokenAndPersistInSession(req, resp, clientId, clientSecret, encodedClientApp, scopes)) { + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setCode(HttpStatus.SC_OK); + HandlerUtil.handleSuccess(resp, proxyResponse); + return; + } + } + HandlerUtil.handleError(resp, null); + } else { + getTokenAndPersistInSession(req, resp, oAuthApp.getClientId(), oAuthApp.getClientSecret(), oAuthApp.getEncodedClientApp(), scopes); } - if (clientAppResponse.getCode() == HttpStatus.SC_CREATED && getTokenAndPersistInSession(req, resp, - clientAppResponse.getData(), scopes)) { - ProxyResponse proxyResponse = new ProxyResponse(); - proxyResponse.setCode(HttpStatus.SC_OK); - HandlerUtil.handleSuccess(resp, proxyResponse); - return; - } - HandlerUtil.handleError(resp, null); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); } catch (JsonSyntaxException e) { @@ -103,57 +144,54 @@ public class LoginHandler extends HttpServlet { } } - /*** + /** * Generates token from token endpoint and persists them inside the session * - * @param req - {@link HttpServletRequest} - * @param clientAppResult - clientAppResult - * @param scopes - scopes defied in the application-mgt.xml - * @throws LoginException - login exception throws when getting token result + * @param req - {@link HttpServletRequest} + * @param resp - {@link HttpServletResponse} + * @param clientId - clientId of the OAuth app + * @param clientSecret - clientSecret of the OAuth app + * @param encodedClientApp - Base64 encoded clientId:clientSecret. + * @param scopes - User scopes JSON Array + * @return boolean response + * @throws LoginException - Throws if any error occurs while getting login response */ private boolean getTokenAndPersistInSession(HttpServletRequest req, HttpServletResponse resp, - String clientAppResult, JsonArray scopes) throws LoginException { + String clientId, String clientSecret, String encodedClientApp, + JsonArray scopes) throws LoginException { JsonParser jsonParser = new JsonParser(); try { - JsonElement jClientAppResult = jsonParser.parse(clientAppResult); - if (jClientAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); - String clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); - String clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); - String encodedClientApp = Base64.getEncoder() - .encodeToString((clientId + HandlerConstants.COLON + clientSecret).getBytes()); - ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp, scopes); + ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp, scopes); - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get token data."); - HandlerUtil.handleError(resp, tokenResultResponse); + if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { + log.error("Error occurred while invoking the API to get token data."); + HandlerUtil.handleError(resp, tokenResultResponse); + return false; + } + String tokenResult = tokenResultResponse.getData(); + if (tokenResult == null) { + log.error("Invalid token response is received."); + HandlerUtil.handleError(resp, tokenResultResponse); + return false; + } + + JsonElement jTokenResult = jsonParser.parse(tokenResult); + if (jTokenResult.isJsonObject()) { + JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); + HttpSession session = req.getSession(false); + if (session == null) { return false; } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - return false; - } - - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - HttpSession session = req.getSession(false); - if (session == null) { - return false; - } - AuthData authData = new AuthData(); - authData.setClientId(clientId); - authData.setClientSecret(clientSecret); - authData.setEncodedClientApp(encodedClientApp); - authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); - session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); - return true; - } + AuthData authData = new AuthData(); + authData.setClientId(clientId); + authData.setClientSecret(clientSecret); + authData.setEncodedClientApp(encodedClientApp); + authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); + authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); + authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); + session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); + return true; } return false; } catch (IOException e) { @@ -167,16 +205,18 @@ public class LoginHandler extends HttpServlet { * Define username and password static parameters. */ private static void validateLoginRequest(HttpServletRequest req) throws LoginException { - String iotsCorePort = System.getProperty("iot.core.https.port"); + String iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTPS_PORT_ENV_VAR); if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) { - iotsCorePort = System.getProperty("iot.core.http.port"); + iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTP_PORT_ENV_VAR); } username = req.getParameter("username"); password = req.getParameter("password"); - gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host") + gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - uiConfigUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host") + uiConfigUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + iotsCorePort + HandlerConstants.UI_CONFIG_ENDPOINT; + iotsCoreUrl = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + iotsCorePort; if (username == null || password == null) { String msg = "Invalid login request. Username or Password is not received for login request."; log.error(msg); @@ -193,7 +233,7 @@ public class LoginHandler extends HttpServlet { * @throws IOException IO exception throws if an error occurred when invoking token endpoint */ private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException { - HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.TOKEN_ENDPOINT); + HttpPost tokenEndpoint = new HttpPost(iotsCoreUrl+ HandlerConstants.TOKEN_ENDPOINT); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); String scopeString = HandlerUtil.getScopeString(scopes); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/OTPInvokerHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/OTPInvokerHandler.java index a97d8be7c5..7194001cca 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/OTPInvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/OTPInvokerHandler.java @@ -241,7 +241,7 @@ public class OTPInvokerHandler extends HttpServlet { private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { String schema = req.getScheme(); - apiEndpoint = schema + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host") + apiEndpoint = schema + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(schema); if (StringUtils.isBlank(req.getHeader(HandlerConstants.OTP_HEADER))) { diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/PermissionScopeHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/PermissionScopeHandler.java new file mode 100644 index 0000000000..96d1d1151f --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/PermissionScopeHandler.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.ui.request.interceptor; + +import io.entgra.ui.request.interceptor.beans.AuthData; +import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import io.entgra.ui.request.interceptor.util.HandlerConstants; +import io.entgra.ui.request.interceptor.util.HandlerUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.json.JSONObject; + +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +@MultipartConfig +@WebServlet("/login-user/scopes") +public class PermissionScopeHandler extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + HttpSession httpSession = req.getSession(false); + if (httpSession == null) { + HandlerUtil.sendUnAuthorizeResponse(resp); + return; + } + + AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); + if (authData == null) { + HandlerUtil.sendUnAuthorizeResponse(resp); + return; + } + + if (!StringUtils.isEmpty(authData.getScope())) { + ProxyResponse proxyResponse = new ProxyResponse(); + JSONObject jsonObject = new JSONObject(); + jsonObject.put(HandlerConstants.USER_SCOPES, authData.getScope()); + proxyResponse.setCode(HttpStatus.SC_OK); + proxyResponse.setData(jsonObject.toString()); + HandlerUtil.handleSuccess(resp, proxyResponse); + } + HandlerUtil.handleError(resp, null); + } +} diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginCallbackHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginCallbackHandler.java index 8ee6ec776b..4bd8a3daaa 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginCallbackHandler.java @@ -49,19 +49,30 @@ public class SsoLoginCallbackHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String code = req.getParameter("code"); HttpSession session = req.getSession(false); - String scope = session.getAttribute("scope").toString(); - String iotsCorePort = System.getProperty("iot.core.https.port"); - + String iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTPS_PORT_ENV_VAR); if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) { - iotsCorePort = System.getProperty("iot.core.http.port"); + iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTP_PORT_ENV_VAR); } - String gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host") + String gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host") + String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + iotsCorePort; - HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.TOKEN_ENDPOINT); + if (session == null) { + String baseContextPath = req.getContextPath(); + String applicationName = baseContextPath.substring(1, baseContextPath.indexOf("-ui-request-handler")); + if (applicationName.equals("entgra")) { + resp.sendRedirect(iotsCoreUrl + "/endpoint-mgt"); + } else { + resp.sendRedirect(iotsCoreUrl + "/" + applicationName); + } + return; + } + + String scope = session.getAttribute("scope").toString(); + + HttpPost tokenEndpoint = new HttpPost(iotsCoreUrl + HandlerConstants.TOKEN_ENDPOINT); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp")); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); @@ -75,11 +86,9 @@ public class SsoLoginCallbackHandler extends HttpServlet { ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); if (jTokenResult.isJsonObject()) { JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - AuthData authData = new AuthData(); authData.setClientId(session.getAttribute("clientId").toString()); authData.setClientSecret(session.getAttribute("clientSecret").toString()); @@ -88,7 +97,6 @@ public class SsoLoginCallbackHandler extends HttpServlet { authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); - resp.sendRedirect(session.getAttribute("redirectUrl").toString()); } } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginHandler.java index 1ade046d43..6ae4c55ed7 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/SsoLoginHandler.java @@ -23,6 +23,9 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; +import io.entgra.ui.request.interceptor.cache.LoginCacheManager; +import io.entgra.ui.request.interceptor.cache.OAuthApp; +import io.entgra.ui.request.interceptor.cache.OAuthAppCacheKey; import io.entgra.ui.request.interceptor.util.HandlerConstants; import io.entgra.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.lang.text.StrSubstitutor; @@ -69,27 +72,66 @@ public class SsoLoginHandler extends HttpServlet { private static String adminPassword; private static String gatewayUrl; private static String iotsCoreUrl; + private static int sessionTimeOut; private static String encodedAdminCredentials; private static String encodedClientApp; private static String applicationId; + private static String applicationName; private static String baseContextPath; private JsonObject uiConfigJsonObject; private HttpSession httpSession; + private LoginCacheManager loginCacheManager; + private OAuthApp oAuthApp; + @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - dynamicClientRegistration(req, resp); - String clientId = httpSession.getAttribute("clientId").toString(); - JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray(); - String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); - String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; - resp.sendRedirect(iotsCoreUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + - "?response_type=code" + - "&client_id=" + clientId + - "&state=" + - "&scope=openid " + scopesSsoString + - "&redirect_uri=" + loginCallbackUrl); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + httpSession = req.getSession(false); + if (httpSession != null) { + httpSession.invalidate(); + } + + httpSession = req.getSession(true); + + initializeAdminCredentials(); + baseContextPath = req.getContextPath(); + applicationName = baseContextPath.substring(1, baseContextPath.indexOf("-ui-request-handler")); + + // Check if oauth app cache is available + loginCacheManager = new LoginCacheManager(); + loginCacheManager.initializeCacheManager(); + oAuthApp = loginCacheManager.getOAuthAppCache( + new OAuthAppCacheKey(applicationName, adminUsername) + ); + + if (oAuthApp == null) { + dynamicClientRegistration(req, resp); + } + + String clientId = oAuthApp.getClientId(); + JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray(); + String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); + String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; + persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), + oAuthApp.getEncodedClientApp(), scopesSsoString); + + resp.sendRedirect(iotsCoreUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + + "?response_type=code" + + "&client_id=" + clientId + + "&state=" + + "&scope=openid " + scopesSsoString + + "&redirect_uri=" + loginCallbackUrl); + } catch (IOException e) { + log.error("Error occurred while sending the response into the socket. ", e); + } catch (JsonSyntaxException e) { + log.error("Error occurred while parsing the response. ", e); + } catch (ParserConfigurationException e) { + log.error("Error while creating the document builder."); + } catch (SAXException e) { + log.error("Error while parsing xml file.", e); + } } /*** @@ -101,39 +143,22 @@ public class SsoLoginHandler extends HttpServlet { */ private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) { try { - File userMgtConf = new File("conf/user-mgt.xml"); - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(userMgtConf); - - adminUsername = doc.getElementsByTagName("UserName").item(0).getTextContent(); - adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent(); - - baseContextPath = req.getContextPath(); - String applicationName = baseContextPath.substring(1, baseContextPath.indexOf("-ui-request-handler")); - - String iotsCorePort = System.getProperty("iot.core.https.port"); + String iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTPS_PORT_ENV_VAR); if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) { - iotsCorePort = System.getProperty("iot.core.http.port"); + iotsCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTP_PORT_ENV_VAR); } - gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host") + gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host") + iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + iotsCorePort; String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; - httpSession = req.getSession(false); - if (httpSession != null) { - httpSession.invalidate(); - } - - httpSession = req.getSession(true); uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); // Register the client application HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); @@ -153,19 +178,22 @@ public class SsoLoginHandler extends HttpServlet { if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { JsonParser jsonParser = new JsonParser(); JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); + String clientId = null; + String clientSecret = null; + if (jClientAppResult.isJsonObject()) { JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); - String clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); - String clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); + clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); + clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()); - String redirectUrl = req.getParameter("redirect"); - httpSession = req.getSession(false); - httpSession.setAttribute("clientId", clientId); - httpSession.setAttribute("clientSecret", clientSecret); - httpSession.setAttribute("encodedClientApp", encodedClientApp); - httpSession.setAttribute("scope", HandlerUtil.getScopeString(scopes)); - httpSession.setAttribute("redirectUrl", redirectUrl); + String scopesString = HandlerUtil.getScopeString(scopes); + persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString); } + + // cache the oauth app credentials + OAuthAppCacheKey oAuthAppCacheKey = new OAuthAppCacheKey(applicationName, adminUsername); + oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp); + loginCacheManager.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); } // Get the details of the registered application @@ -211,7 +239,7 @@ public class SsoLoginHandler extends HttpServlet { ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); // Update app as a SaaS app - this.updateSaasApp(applicationName); + this.updateSaasApp(applicationId); if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); @@ -221,7 +249,6 @@ public class SsoLoginHandler extends HttpServlet { if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_OK) { return; } - HandlerUtil.handleError(resp, null); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); @@ -229,11 +256,49 @@ public class SsoLoginHandler extends HttpServlet { log.error("Error occurred while parsing the response. ", e); } catch (ParserConfigurationException e) { log.error("Error while creating the document builder."); - } catch ( SAXException e) { + } catch (SAXException e) { log.error("Error while parsing xml file.", e); } } + /** + * Initialize the admin credential variables + * + * @throws ParserConfigurationException - Throws when error occur during initializing the document builder + * @throws IOException - Throws when error occur during document parsing + * @throws SAXException - Throws when error occur during document parsing + */ + private void initializeAdminCredentials() throws ParserConfigurationException, IOException, SAXException { + File userMgtConf = new File("repository/conf/user-mgt.xml"); + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(userMgtConf); + + adminUsername = doc.getElementsByTagName("UserName").item(0).getTextContent(); + adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent(); + } + + + /** + * Persist the Auth data inside the session + * + * @param req - Http Servlet request + * @param clientId - Client ID of the SP + * @param clientSecret - Client secret of the SP + * @param encodedClientApp - Base64 encoded clientId:clientSecret. + * @param scopes - User scopes + */ + private void persistAuthSessionData(HttpServletRequest req, String clientId, String clientSecret, + String encodedClientApp, String scopes) { + httpSession = req.getSession(false); + httpSession.setAttribute("clientId", clientId); + httpSession.setAttribute("clientSecret", clientSecret); + httpSession.setAttribute("encodedClientApp", encodedClientApp); + httpSession.setAttribute("scope", scopes); + httpSession.setAttribute("redirectUrl", req.getParameter("redirect")); + httpSession.setMaxInactiveInterval(sessionTimeOut); + } + /*** * Generates payload for application grant_type update payload * @@ -262,7 +327,7 @@ public class SsoLoginHandler extends HttpServlet { * @throws IOException IO exception throws if an error occurred when invoking token endpoint */ private ProxyResponse getTokenResult(String encodedClientApp) throws IOException { - HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.TOKEN_ENDPOINT); + HttpPost tokenEndpoint = new HttpPost(iotsCoreUrl + HandlerConstants.TOKEN_ENDPOINT); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); @@ -311,7 +376,7 @@ public class SsoLoginHandler extends HttpServlet { */ private void updateSaasApp(String appName) throws ParserConfigurationException, IOException, SAXException { File getAppRequestXmlFile = new File(HandlerConstants.PAYLOADS_DIR + "/get-app-request.xml"); - String identityAppMgtUrl = iotsCoreUrl + HandlerConstants.IDENTITY_APP_MGT_ENDPOINT;; + String identityAppMgtUrl = iotsCoreUrl + HandlerConstants.IDENTITY_APP_MGT_ENDPOINT; HttpPost getApplicationEndpoint = new HttpPost(identityAppMgtUrl); getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java index 9686979d53..c545567ed8 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java @@ -33,6 +33,8 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -41,6 +43,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Base64; @MultipartConfig @WebServlet("/user") @@ -52,8 +55,9 @@ public class UserHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { String serverUrl = - req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.gateway.host") - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); HttpSession httpSession = req.getSession(false); if (httpSession == null) { HandlerUtil.sendUnAuthorizeResponse(resp); @@ -70,6 +74,11 @@ public class UserHandler extends HttpServlet { HttpPost tokenEndpoint = new HttpPost(serverUrl + HandlerConstants.INTROSPECT_ENDPOINT); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); + String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername(); + String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); + tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() + .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); StringEntity tokenEPPayload = new StringEntity("token=" + accessToken, ContentType.APPLICATION_FORM_URLENCODED); tokenEndpoint.setEntity(tokenEPPayload); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/LoginCacheManager.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/LoginCacheManager.java new file mode 100644 index 0000000000..3ecd741350 --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/LoginCacheManager.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.ui.request.interceptor.cache; + +import io.entgra.ui.request.interceptor.util.HandlerConstants; + +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.Caching; + +/** + * Contains necessary functions to manage oAuth app cache during login handling + */ +public class LoginCacheManager { + + private CacheManager cacheManager = null; + private Cache cache = null; + + /** + * Initialize the cache manager if it is not already initialized + */ + public void initializeCacheManager() { + cacheManager = Caching.getCacheManagerFactory().getCacheManager(HandlerConstants.LOGIN_CACHE); + } + + /** + * Persists OAuth app cache if it is not already persisted + * + * @param oAuthAppCacheKey - The identifier key of the cache + * @param oAuthApp - The value of the cache which contains OAuth app data + */ + public void addOAuthAppToCache(OAuthAppCacheKey oAuthAppCacheKey, OAuthApp oAuthApp) { + cache = cacheManager.getCache(HandlerConstants.LOGIN_CACHE); + cache.put(oAuthAppCacheKey, oAuthApp); + } + + /** + * Retrieves the OAuth app cache + * + * @param oAuthAppCacheKey - The key to identify the cache + * @return - Returns OAuthApp object + */ + public OAuthApp getOAuthAppCache(OAuthAppCacheKey oAuthAppCacheKey) { + cache = cacheManager.getCache(HandlerConstants.LOGIN_CACHE); + return cache.get(oAuthAppCacheKey); + } +} diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthApp.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthApp.java new file mode 100644 index 0000000000..db721ea992 --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthApp.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.ui.request.interceptor.cache; + +/** + * The data object used for Login Cache + */ +public class OAuthApp { + + private String appName; + private String appOwner; + private String clientId; + private String clientSecret; + private String encodedClientApp; + + public OAuthApp(String appName, String appOwner, String clientId, String clientSecret, String encodedClientApp) { + this.appName = appName; + this.appOwner = appOwner; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.encodedClientApp = encodedClientApp; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getAppOwner() { + return appOwner; + } + + public void setAppOwner(String appOwner) { + this.appOwner = appOwner; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getEncodedClientApp() { + return encodedClientApp; + } + + public void setEncodedClientApp(String encodedClientApp) { + this.encodedClientApp = encodedClientApp; + } +} diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthAppCacheKey.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthAppCacheKey.java new file mode 100644 index 0000000000..aa03eade5a --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/cache/OAuthAppCacheKey.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.ui.request.interceptor.cache; + +import java.util.Objects; + +/** + * The key object used for Login Cache + */ +public class OAuthAppCacheKey { + + private String appName; + private String appOwner; + private volatile int hashCode; + + public OAuthAppCacheKey(String appName, String appOwner) { + this.appName = appName; + this.appOwner = appOwner; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getAppOwner() { + return appOwner; + } + + public void setAppOwner(String appOwner) { + this.appOwner = appOwner; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (obj instanceof OAuthAppCacheKey) { + final OAuthAppCacheKey other = (OAuthAppCacheKey) obj; + String thisId = this.appName + "-" + this.appOwner; + String otherId = other.appName + "-" + other.appOwner; + return thisId.equals(otherId); + } + return false; + } + + @Override + public int hashCode() { + if (hashCode == 0) { + hashCode = Objects.hash(appName, appOwner); + } + return hashCode; + } +} diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java index 3d4255c0aa..4c864c81e5 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java @@ -22,10 +22,10 @@ public class HandlerConstants { public static final String PUBLISHER_APPLICATION_NAME = "application-mgt-publisher"; public static final String APP_REG_ENDPOINT = "/api-application-registration/register"; public static final String UI_CONFIG_ENDPOINT = "/api/device-mgt-config/v1.0/configurations/ui-config"; - public static final String TOKEN_ENDPOINT = "/token"; + public static final String TOKEN_ENDPOINT = "/oauth2/token"; public static final String INTROSPECT_ENDPOINT = "/oauth2/introspect"; public static final String AUTHORIZATION_ENDPOINT = "/oauth2/authorize"; - public static final String APIM_APPLICATIONS_ENDPOINT = "/api/am/store/v0.12/applications/"; + public static final String APIM_APPLICATIONS_ENDPOINT = "/api/am/devportal/v2/applications/"; public static final String IDENTITY_APP_MGT_ENDPOINT = "/services/IdentityApplicationManagementService.IdentityApplicationManagementServiceHttpsSoap11Endpoint"; public static final String LOGIN_PAGE = "/login"; public static final String SSO_LOGIN_CALLBACK = "/ssoLoginCallback"; @@ -55,10 +55,12 @@ public class HandlerConstants { public static final String PASSWORD_GRANT_TYPE = "password"; public static final String JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public static final String PRODUCTION_KEY = "PRODUCTION"; + public static final String LOGIN_CACHE = "LOGIN_CACHE"; public static final String SCHEME_SEPARATOR = "://"; public static final String COLON = ":"; public static final String HTTP_PROTOCOL = "http"; + public static final String HTTPS_PROTOCOL = "https"; public static final String UNDERSCORE = "_"; public static final int INTERNAL_ERROR_CODE = 500; @@ -66,7 +68,7 @@ public class HandlerConstants { public static final String OTP_HEADER = "one-time-token"; - public static final String AX_PREFIX = "ax2317:"; + public static final String AX_PREFIX = "ax2251:"; public static final String PAYLOADS_DIR = "repository/resources/payloads"; public static final String SOAP_ACTION_HEADER = "SOAPAction"; @@ -74,6 +76,10 @@ public class HandlerConstants { public static final String REMOTE_SESSION_CONTEXT = "/remote/session/clients"; public static final String IOT_CORE_HOST_ENV_VAR = "iot.core.host"; - public static final String IOT_CORE_PORT_ENV_VAR = "iot.core.https.port"; - + public static final String IOT_CORE_HTTP_PORT_ENV_VAR = "iot.core.http.port"; + public static final String IOT_CORE_HTTPS_PORT_ENV_VAR = "iot.core.https.port"; + public static final String IOT_GW_HOST_ENV_VAR = "iot.gateway.host"; + public static final String IOT_GW_HTTP_PORT_ENV_VAR = "iot.gateway.http.port"; + public static final String IOT_GW_HTTPS_PORT_ENV_VAR = "iot.gateway.https.port"; + public static final String USER_SCOPES = "userScopes"; } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java index 4582468a0c..5acec832ce 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java @@ -226,9 +226,9 @@ public class HandlerUtil { * @return {@link String} gateway port */ public static String getGatewayPort(String scheme) { - String gatewayPort = System.getProperty("iot.gateway.https.port"); + String gatewayPort = System.getProperty(HandlerConstants.IOT_GW_HTTPS_PORT_ENV_VAR); if (HandlerConstants.HTTP_PROTOCOL.equals(scheme)) { - gatewayPort = System.getProperty("iot.gateway.http.port"); + gatewayPort = System.getProperty(HandlerConstants.IOT_GW_HTTP_PORT_ENV_VAR); } return gatewayPort; } @@ -240,9 +240,9 @@ public class HandlerUtil { * @return {@link String} gateway port */ public static String getCorePort(String scheme) { - String productCorePort = System.getProperty("iot.core.https.port"); + String productCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTPS_PORT_ENV_VAR); if (HandlerConstants.HTTP_PROTOCOL.equals(scheme)) { - productCorePort = System.getProperty("iot.core.https.por"); + productCorePort = System.getProperty(HandlerConstants.IOT_CORE_HTTP_PORT_ENV_VAR); } return productCorePort; } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/META-INF/webapp-classloading.xml b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/META-INF/webapp-classloading.xml index cc5b3c66d7..9f50930c4f 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/META-INF/webapp-classloading.xml +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/webapp/META-INF/webapp-classloading.xml @@ -31,5 +31,5 @@ Tomcat environment is the default and every webapps gets it even if they didn't specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF. --> - Carbon + CXF3,Carbon diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index cfed28d8b0..6204dc57d3 100644 --- a/components/ui-request-interceptor/pom.xml +++ b/components/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 2d3df3e061..e041b45f83 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -21,14 +21,13 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt org.wso2.carbon.webapp.authenticator.framework - 4.1.16-SNAPSHOT bundle WSO2 Carbon - Web Application Authenticator Framework Bundle WSO2 Carbon - Web Application Authenticator Framework Bundle @@ -63,13 +62,13 @@ javax.xml.bind.annotation, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, javax.xml.validation, - org.apache.catalina, - org.apache.catalina.connector, - org.apache.catalina.util, + + + org.apache.commons.logging, - org.apache.coyote, - org.apache.tomcat.util.buf, - org.apache.tomcat.util.http, + + + org.osgi.service.component, org.osgi.framework, org.w3c.dom, @@ -106,7 +105,7 @@ org.apache.commons.pool.impl, org.apache.http.conn, org.apache.http.impl.conn, - javax.xml.soap; version="${javax.xml.soap.imp.pkg.version}", + javax.xml.stream, org.apache.axiom.*; version="${axiom.osgi.version.range}", org.wso2.carbon.registry.core.*, diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index 4a3c39e174..922e3fdcf5 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt webapp-authenticator-framework - 4.1.16-SNAPSHOT pom WSO2 Carbon - Webapp Authenticator Framework http://wso2.org diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml index e97519888a..b1033f9963 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/pom.xml @@ -21,14 +21,13 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.application.extension.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - API Management Application Extension Feature http://wso2.org This feature contains an implementation of a api application registration, which takes care of subscription diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf index 1d8124571f..61654c2892 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/p2.inf @@ -1,3 +1,5 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.application.extension_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.application.extension_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.application.extension_${feature.version}/synapse-configs/default/api/_API_Application_Registration_.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/_API_Application_Registration_.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.application.extension_${feature.version}/synapse-configs/default/sequences/_api_registration_fault_.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/sequences/_api_registration_fault_.xml,overwrite:true);\ diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/api/_API_Application_Registration_.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/api/_API_Application_Registration_.xml new file mode 100644 index 0000000000..7e25c01342 --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/api/_API_Application_Registration_.xml @@ -0,0 +1,63 @@ + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + + + + + 60000 + fault + + + + + + + + + + + + + + \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/sequences/_api_registration_fault_.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/sequences/_api_registration_fault_.xml new file mode 100644 index 0000000000..335a9abaf3 --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.feature/src/main/resources/synapse-configs/default/sequences/_api_registration_fault_.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml index 6e332ef23b..2bd2ef8468 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.handler.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.handler.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Management - APIM handler Server Feature http://wso2.org This feature contains the handler for the api authentications diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml index a934c7dc4c..8051e07759 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.integration.client.feature/pom.xml @@ -21,13 +21,12 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.integration.client.feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - APIM Integration Client Feature http://wso2.org diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml index e9f713c97f..d8c6d64729 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/pom.xml @@ -21,14 +21,13 @@ org.wso2.carbon.devicemgt apimgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - API Management Webapp Publisher Feature http://wso2.org This feature contains an implementation of a Tomcat lifecycle listener, which takes care of publishing diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-publisher-config.xml.j2 b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-publisher-config.xml.j2 new file mode 100644 index 0000000000..d8a0413ec8 --- /dev/null +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-publisher-config.xml.j2 @@ -0,0 +1,56 @@ + + + + + + + + {% if webapp_publisher_configs.host is defined %} + {{webapp_publisher_configs.host}} + {% else %} + https://${iot.core.host}:${iot.core.https.port} + {% endif %} + + + {% if webapp_publisher_configs.publish_api is defined %} + {{webapp_publisher_configs.publish_api}} + {% else %} + true + {% endif %} + + + {% if webapp_publisher_configs.enable_update_api is defined %} + {{webapp_publisher_configs.enable_update_api}} + {% else %} + true + {% endif %} + + + + default + {% if webapp_publisher_configs.profiles is defined %} + {%- for profile in webapp_publisher_configs.profiles -%} + {{profile}} + {% endfor %} + {% endif %} + + \ No newline at end of file diff --git a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/p2.inf b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/p2.inf index 3d6782a96f..8b5d94e410 100644 --- a/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/p2.inf +++ b/features/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher.feature/src/main/resources/p2.inf @@ -1,2 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.webapp.publisher_${feature.version}/conf/webapp-publisher-config.xml,target:${installFolder}/../../conf/etc/webapp-publisher-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.apimgt.webapp.publisher_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 201296d7d7..42650878ae 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,23 +22,20 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt apimgt-extensions-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - API Management Extensions Feature http://wso2.org - org.wso2.carbon.apimgt.integration.client.feature org.wso2.carbon.apimgt.webapp.publisher.feature org.wso2.carbon.apimgt.application.extension.feature - org.wso2.carbon.apimgt.handler.server.feature diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.api.feature/pom.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.api.feature/pom.xml index 44f13b7540..5bdf583f19 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.api.feature/pom.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.api.feature/pom.xml @@ -22,13 +22,12 @@ org.wso2.carbon.devicemgt application-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.api.feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Application Management API Feature https://entgra.io diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml index d8a8448fac..66d0322843 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt application-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.application.mgt.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Application Management Server Feature https://entgra.io @@ -60,6 +59,10 @@ cxf-rt-frontend-jaxrs ${cxf.version} + + com.h2database.wso2 + h2-database-engine + @@ -108,6 +111,39 @@ + + org.apache.maven.plugins + maven-antrun-plugin + + + create-app-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + org.wso2.maven carbon-p2-plugin diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml index ddeeaa5005..9e91286a79 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf/datasources/application-mgt-datasources.xml @@ -30,7 +30,7 @@ - jdbc:h2:repository/database/WSO2DM_APPM_DB;DB_CLOSE_ON_EXIT=FALSE + jdbc:h2:./repository/database/WSO2DM_APPM_DB;DB_CLOSE_ON_EXIT=FALSE wso2carbon wso2carbon org.h2.Driver diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 new file mode 100644 index 0000000000..2550288629 --- /dev/null +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 @@ -0,0 +1,231 @@ + + + + + + jdbc/APPM_DS + + + + {% if application_mgt_conf.extension.application_manager is defined %} + {{application_mgt_conf.extension.application_manager}} + {% else %} + org.wso2.carbon.device.application.mgt.core.impl.ApplicationManagerImpl + {% endif %} + + + {% if application_mgt_conf.extension.review_manager is defined %} + {{application_mgt_conf.extension.review_manager}} + {% else %} + org.wso2.carbon.device.application.mgt.core.impl.ReviewManagerImpl + {% endif %} + + + {% if application_mgt_conf.extension.life_cycle_state_manager is defined %} + {{application_mgt_conf.extension.life_cycle_state_manager}} + {% else %} + org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager + {% endif %} + + + {% if application_mgt_conf.extension.subscription_manager is defined %} + {{application_mgt_conf.extension.subscription_manager}} + {% else %} + org.wso2.carbon.device.application.mgt.core.impl.SubscriptionManagerImpl + {% endif %} + + + {% if application_mgt_conf.extension.application_storage_manager is defined %} + {{application_mgt_conf.extension.application_storage_manager}} + {% if application_mgt_conf.extension.application_storage_manager.parameter_options is defined %} + + {% for property_name,property_value in application_mgt_conf.extension.application_storage_manager.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% endif %} + {% else %} + org.wso2.carbon.device.application.mgt.core.impl.ApplicationStorageManagerImpl + + repository/resources/apps/ + 6 + + {% endif %} + + + + + + + + + + true + true + true + /app-mgt/life-cycle/application/create + + In-Review + + + + /app-mgt/life-cycle/application/review + + Rejected + Approved + Created + + + + /app-mgt/life-cycle/application/approve + + In-Review + Published + + + + true + /app-mgt/life-cycle/application/reject + + In-Review + + + + true + /app-mgt/life-cycle/application/publish + + Blocked + Deprecated + + + + /app-mgt/life-cycle/application/block + + Published + Deprecated + + + + /app-mgt/life-cycle/application/deprecate + + Published + Retired + + + + true + /app-mgt/life-cycle/application/retire + + + + + EMM + IoT + Art & Design + Auto & Vehicles + Beauty + Books & Reference + Business + Comics + Communications + Dating + Education + Entertainment + Events + Finance + Food & Drink + Health & Fitness + House & Home + Libraries & Demo + Lifestyle + Maps & Navigation + Medical + Music & Audio + News & Magazines + Parenting + Personalization + Photography + Productivity + Shopping + Social + Sports + Tools + Travel & Local + Video Players & Editors + Weather + GooglePlaySyncedApp + {% if application_mgt_conf.app_categories is defined %} + {%- for app_category in application_mgt_conf.app_categories -%} + {{app_category}} + {% endfor %} + {% endif %} + + + + {% if application_mgt_conf.rating_conf.min_rating_value is defined %} + {{application_mgt_conf.rating_conf.min_rating_value}} + {% else %} + 1 + {% endif %} + {% if application_mgt_conf.rating_conf.max_rating_value is defined %} + {{application_mgt_conf.rating_conf.max_rating_value}} + {% else %} + 10 + {% endif %} + + + + {% if application_mgt_conf.mdm_conf.artifact_download_protocol is defined %} + {{application_mgt_conf.mdm_conf.artifact_download_protocol}} + {% else %} + http + {% endif %} + + {% if application_mgt_conf.mdm_conf.artifact_download_endpoint is defined %} + {{application_mgt_conf.mdm_conf.artifact_download_endpoint}} + {% else %} + /api/application-mgt/v1.0/artifact + {% endif %} + + diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/application-mgt-datasources.xml.j2 b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/application-mgt-datasources.xml.j2 new file mode 100644 index 0000000000..a25faf6511 --- /dev/null +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/application-mgt-datasources.xml.j2 @@ -0,0 +1,59 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + + APPM_DS + The datasource used for CDM Application Management + + jdbc/APPM_DS + + + + {% if database.app_mgt is defined %} + {{database.app_mgt.url}} + {{database.app_mgt.username}} + {{database.app_mgt.password}} + {{database.app_mgt.driver}} + {{database.app_mgt.validationQuery}} + {% for property_name,property_value in database.app_mgt.pool_options.items() %} + <{{property_name}}>{{property_value}} + {% endfor %} + {% else %} + jdbc:h2:./repository/database/WSO2DM_APPM_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + {% endif %} + + + + + + diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index f16927301b..dcbebd74b4 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -269,7 +269,7 @@ CREATE TABLE IF NOT EXISTS AP_SCHEDULED_SUBSCRIPTION( APPLICATION_UUID VARCHAR(36) NOT NULL, SUBSCRIBER_LIST LONGVARCHAR NOT NULL, STATUS VARCHAR(15) NOT NULL, - SCHEDULED_AT TIMESTAMP NOT NULL, + SCHEDULED_AT BIGINT NOT NULL, SCHEDULED_BY VARCHAR(100) NOT NULL, SCHEDULED_TIMESTAMP TIMESTAMP NOT NULL, DELETED BOOLEAN, diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql index 78e05c1371..25fc47e38e 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mssql.sql @@ -270,7 +270,7 @@ CREATE TABLE AP_SCHEDULED_SUBSCRIPTION( APPLICATION_UUID VARCHAR(200) NOT NULL, SUBSCRIBER_LIST VARCHAR(MAX) NOT NULL, STATUS VARCHAR(15) NOT NULL, - SCHEDULED_AT DATETIME2(0) NOT NULL, + SCHEDULED_AT BIGINT NOT NULL, SCHEDULED_BY VARCHAR(100) NOT NULL, SCHEDULED_TIMESTAMP DATETIME2(0) NOT NULL, DELETED BIT, diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 1daa796858..5d5db38b2d 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -269,7 +269,7 @@ CREATE TABLE IF NOT EXISTS AP_SCHEDULED_SUBSCRIPTION( APPLICATION_UUID VARCHAR(36) NOT NULL, SUBSCRIBER_LIST TEXT NOT NULL, STATUS VARCHAR(15) NOT NULL, - SCHEDULED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, + SCHEDULED_AT BIGINT NOT NULL, SCHEDULED_BY VARCHAR(100) NOT NULL, SCHEDULED_TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, DELETED BOOLEAN, diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql index c4f2c99f06..edbc277ab2 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/oracle.sql @@ -372,7 +372,7 @@ CREATE TABLE AP_SCHEDULED_SUBSCRIPTION ( APPLICATION_UUID VARCHAR(36) NOT NULL, SUBSCRIBER_LIST VARCHAR(4000) NOT NULL, STATUS VARCHAR(15) NOT NULL, - SCHEDULED_AT TIMESTAMP NOT NULL, + SCHEDULED_AT NUMBER(19) NOT NULL, SCHEDULED_BY VARCHAR(100) NOT NULL, SCHEDULED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, DELETED NUMBER(1) NOT_NULL DEFAULT 0, diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql index 5c20aa4a75..d871549d89 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/postgresql.sql @@ -299,7 +299,7 @@ CREATE TABLE IF NOT EXISTS AP_SCHEDULED_SUBSCRIPTION( APPLICATION_UUID VARCHAR(36) NOT NULL, SUBSCRIBER_LIST TEXT NOT NULL, STATUS VARCHAR(15) NOT NULL, - SCHEDULED_AT TIMESTAMP(0) DEFAULT CURRENT_TIMESTAMP NOT NULL, + SCHEDULED_AT BIGINT NOT NULL, SCHEDULED_BY VARCHAR(100) NOT NULL, SCHEDULED_TIMESTAMP TIMESTAMP(0) DEFAULT CURRENT_TIMESTAMP NOT NULL, DELETED BOOLEAN, diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/p2.inf b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/p2.inf index a12c244131..360d6ef9f9 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/p2.inf +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/p2.inf @@ -1,7 +1,9 @@ instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.application.mgt.server_${feature.version}/database/,target:${installFolder}/../../../repository/database/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.application.mgt.server_${feature.version}/conf/application-mgt.xml,target:${installFolder}/../../conf/application-mgt.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.application.mgt.server_${feature.version}/conf/datasources/application-mgt-datasources.xml,target:${installFolder}/../../conf/datasources/application-mgt-datasources.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.application.mgt.server_${feature.version}/dbscripts/cdm/application-mgt,target:${installFolder}/../../../dbscripts/cdm/application-mgt,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.application.mgt.server_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ instructions.unconfigure = \ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/application-mgt-datasources.xml);\ diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index 86fe383b78..1aa070544a 100644 --- a/features/application-mgt/pom.xml +++ b/features/application-mgt/pom.xml @@ -22,13 +22,12 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 application-mgt-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Application Management Feature https://entgra.io diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml index 1988d44d71..c4894c3c43 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 1dfc80f494..5cbef9678b 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml index a7a9d89595..6792ce5d05 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt certificate-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Certificate Management Server Feature http://wso2.org This feature contains the core bundles required for back-end Certificate Management functionality diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/certificate-config.xml.j2 b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/certificate-config.xml.j2 new file mode 100755 index 0000000000..2ffad144e2 --- /dev/null +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/certificate-config.xml.j2 @@ -0,0 +1,47 @@ + + + + {% if certificate_conf.certificate_keystore is defined %} + + {{certificate_conf.certificate_keystore.location}} + + {{certificate_conf.certificate_keystore.type}} + + {{certificate_conf.certificate_keystore.password}} + + {{certificate_conf.certificate_keystore.cacert_alias}} + + {{certificate_conf.certificate_keystore.cacert_password}} + + {{certificate_conf.certificate_keystore.racert_alias}} + + {{certificate_conf.certificate_keystore.racert_password}} + {% else %} + + ${carbon.home}/repository/resources/security/wso2certs.jks + + JKS + + wso2carbon + + cacert + + cacert + + racert + + racert + {% endif %} + + + + + + + jdbc/DM_DS + + + + + 10 + \ No newline at end of file diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf index ef6d64fc87..345f751daa 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/p2.inf @@ -1,4 +1,5 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/wso2certs.jks,target:${installFolder}/../../resources/security/wso2certs.jks,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf/certificate-config.xml,target:${installFolder}/../../conf/certificate-config.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.server_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index bce727f0f2..7dceadff12 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,14 +22,12 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 - org.wso2.carbon.devicemgt certificate-mgt-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Certificate Management Feature http://wso2.org diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml index 367a9e97dd..aca2bf216d 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.device.type.deployer.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Type Deployer Feature http://wso2.org WSO2 Carbon - Device Type Deployer Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index 3a9724ec93..e1caa4a07d 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - FCM Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index 03ab72d6f5..489e36b2cd 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - MQTT Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index 87c6f51c3e..4c025f8572 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - MQTT Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - MQTT Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index 7f49e2dd7a..f482a4874f 100644 --- a/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - XMPP Based Push Notification Provider Feature http://wso2.org WSO2 Carbon - XMPP Based Push Notification Provider Feature diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 8f4033f2f0..063ed9e1c2 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml index 4f2154e29d..411d4d0a2c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.analytics.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.analytics.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Management Server Feature http://wso2.org This feature contains bundles related to device analytics data publisher and ws proxy diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index 68ac18bdf9..c36f6b292c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml index 055fcd0a57..f96f388520 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -43,34 +43,6 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - - - org.wso2.carbon.registry - org.wso2.carbon.registry.indexing - - - org.wso2.carbon.analytics-common - org.wso2.carbon.event.receiver.stub - - - org.wso2.carbon.analytics-common - org.wso2.carbon.event.stream.stub - - - org.wso2.carbon.analytics-common - org.wso2.carbon.event.publisher.stub - - - org.wso2.carbon.analytics-common - org.wso2.carbon.event.stream.persistence.stub - - - org.wso2.orbit.org.scannotation - scannotation - @@ -127,27 +99,6 @@ org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.common:${carbon.device.mgt.version} - - org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.analytics.data.publisher:${carbon.device.mgt.version} - - - org.wso2.carbon.analytics-common:org.wso2.carbon.event.receiver.stub:${carbon.analytics.common.version} - - - org.wso2.carbon.analytics-common:org.wso2.carbon.event.stream.stub:${carbon.analytics.common.version} - - - org.wso2.carbon.analytics-common:org.wso2.carbon.event.publisher.stub:${carbon.analytics.common.version} - - - org.wso2.carbon.analytics-common:org.wso2.carbon.event.stream.persistence.stub:${carbon.analytics.common.version} - - - org.wso2.orbit.com.fasterxml.jackson.core:jackson-annotations:${jackson-annotations.version} - - - org.wso2.orbit.org.scannotation:scannotation:${scannotation.version} - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--OAuth2TokenManagement.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--OAuth2TokenManagement.xml index 9e7e2fd601..637f40f776 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--OAuth2TokenManagement.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--OAuth2TokenManagement.xml @@ -20,7 +20,6 @@ - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--UserManagementValidateUser.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--UserManagementValidateUser.xml index 5b8ee2f562..ec61d66eec 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--UserManagementValidateUser.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/apis/admin--UserManagementValidateUser.xml @@ -20,7 +20,6 @@ - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml new file mode 100755 index 0000000000..78db49688e --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/datasources/cdm-datasources.xml @@ -0,0 +1,65 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + DM_DS + The datasource used for CDM + + jdbc/DM_DS + + + + jdbc:h2:./repository/database/WSO2DM_DB;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + DM_ARCHIVAL_DS + The archival datasource used for CDM + + jdbc/DM_ARCHIVAL_DS + + + + jdbc:h2:./repository/database/WSO2DM_ARCHIVAL_DS;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index a0ba89e8b7..36fe025034 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -20,6 +20,8 @@ true true + + 3600 application_management @@ -177,6 +179,8 @@ perm:metadata:view perm:metadata:create perm:metadata:update + perm:android:google-account + perm:android:update-default-sim device-mgt diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 new file mode 100644 index 0000000000..214ad3f8a8 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 @@ -0,0 +1,315 @@ + + + + + + + + jdbc/DM_DS + + + + + {% if device_mgt_conf.push_notification_conf is defined %} + {{device_mgt_conf.push_notification_conf.scheduler_batch_size}} + {{device_mgt_conf.push_notification_conf.scheduler_batch_delay_mills}} + {{device_mgt_conf.push_notification_conf.scheduler_task_initial_delay}} + {{device_mgt_conf.push_notification_conf.scheduler_task_enabled}} + {% else %} + 1000 + 60000 + 60000 + true + {% endif %} + + org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider + org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider + org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider + org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider + {% if device_mgt_conf.push_notification_conf.push_notification_providers is defined %} + {%- for push_notification_provider in device_mgt_conf.push_notification_conf.push_notification_providers -%} + {{push_notification_provider}} + {% endfor %} + {% endif %} + + + + {% if device_mgt_conf.pull_notification_conf is defined %} + {{device_mgt_conf.pull_notification_conf.enabled}} + {% else %} + false + {% endif %} + + + {% if device_mgt_conf.identity_conf is defined %} + {{device_mgt_conf.identity_conf.server_url}} + {{device_mgt_conf.identity_conf.admin_username}} + {{device_mgt_conf.identity_conf.admin_password}} + {% else %} + https://localhost:9443 + admin + admin + {% endif %} + + + {% if device_mgt_conf.key_manager_conf is defined %} + {{device_mgt_conf.key_manager_conf.server_url}} + {{device_mgt_conf.key_manager_conf.admin_username}} + {{device_mgt_conf.key_manager_conf.admin_password}} + {% else %} + https://localhost:9443 + admin + admin + {% endif %} + + + {% if device_mgt_conf.policy_conf is defined %} + {{device_mgt_conf.policy_conf.monitoring_class}} + {{device_mgt_conf.policy_conf.monitoring_enable}} + {{device_mgt_conf.policy_conf.monitoring_frequency}} + {{device_mgt_conf.policy_conf.max_retries}} + {{device_mgt_conf.policy_conf.min_retries_to_mark_unreachable}} + {{device_mgt_conf.policy_conf.min_retries-to_mark_inactive}} + + + + {{device_mgt_conf.policy_conf.policy.evaluation_point}} + {{device_mgt_conf.policy_conf.cache_enable}} + {% else %} + org.wso2.carbon.policy.mgt + true + 60000 + 5 + 8 + 20 + + + + Simple + true + {% endif %} + + + + {% if device_mgt_conf.pagination_conf is defined %} + {{device_mgt_conf.pagination_conf.device_list_page_size}} + {{device_mgt_conf.pagination_conf.group_list_page_size}} + {{device_mgt_conf.pagination_conf.notification_list_page_size}} + {{device_mgt_conf.pagination_conf.activity_list_page_size}} + {{device_mgt_conf.pagination_conf.operation_list_page_size}} + {{device_mgt_conf.pagination_conf.topic_list_page_size}} + {{device_mgt_conf.pagination_conf.metadata_list_page_size}} + {% else %} + 20 + 20 + 20 + 20 + 20 + 20 + 20 + {% endif %} + + + + {% if device_mgt_conf.device_status_task_config is defined %} + {{device_mgt_conf.device_status_task_config.enable}} + {% else %} + true + {% endif %} + + + + {% if device_mgt_conf.device_cache_conf is defined %} + {{device_mgt_conf.device_cache_conf.enable}} + {{device_mgt_conf.device_cache_conf.expiry_time}} + + {{device_mgt_conf.device_cache_conf.capacity}} + {% else %} + true + 600 + + 10000 + {% endif %} + + + {% if device_mgt_conf.geo_fence_cache_conf is defined %} + {{device_mgt_conf.geo_fence_cache_conf.enable}} + {{device_mgt_conf.geo_fence_cache_conf.expiry_time}} + {{device_mgt_conf.geo_fence_cache_conf.capacity}} + {% else %} + true + 600 + 10000 + {% endif %} + + + {% if device_mgt_conf.event_operation_task_conf is defined %} + {{device_mgt_conf.event_operation_task_conf.enable}} + {% else %} + true + {% endif %} + + + {% if device_mgt_conf.certificate_cache_conf is defined %} + {{device_mgt_conf.certificate_cache_conf.enable}} + {{device_mgt_conf.certificate_cache_conf.expiry_time}} + {% else %} + true + 86400 + {% endif %} + + + + + jdbc/DM_ARCHIVAL_DS + + + + {% if device_mgt_conf.archival_conf.archival_task is defined %} + {{device_mgt_conf.archival_conf.archival_task.enabled}} + {{device_mgt_conf.archival_conf.archival_task.archival_pending_operations}} + + DM_DB + ARCHIVAL_DB + + {{device_mgt_conf.archival_conf.archival_task.task_class}} + + {{device_mgt_conf.archival_conf.archival_task.cron_expression}} + + {{device_mgt_conf.archival_conf.archival_task.retention_period}} + {{device_mgt_conf.archival_conf.archival_task.execution_batch_size}} + + {{device_mgt_conf.archival_conf.archival_task.purging_task.enabled}} + {{device_mgt_conf.archival_conf.archival_task.purging_task.task_class}} + + {{device_mgt_conf.archival_conf.archival_task.purging_task.cron_expression}} + + {{device_mgt_conf.archival_conf.archival_task.purging_task.retention_period}} + + {% else %} + false + false + + DM_DB + ARCHIVAL_DB + + org.wso2.carbon.device.mgt.core.task.impl.ArchivalTask + + 0 0 0 1/1 * ? * + + 30 + 1000 + + false + org.wso2.carbon.device.mgt.core.task.impl.ArchivedDataDeletionTask + + 0 0 3 1/1 * ? * + + 365 + + {% endif %} + + + + {% if device_mgt_conf.geo_location_conf is defined %} + {{device_mgt_conf.geo_location_conf.enabled}} + {% else %} + false + {% endif %} + + + false + false + + false + + + + + * + + + + + + {% if device_mgt_conf.remote_session_conf is defined %} + {{device_mgt_conf.remote_session_conf.enabled}} + {{device_mgt_conf.remote_session_conf.remote_session_server_url}} + {{device_mgt_conf.remote_session_conf.max_http_connection_per_host}} + {{device_mgt_conf.remote_session_conf.max_total_http_connections}} + {{device_mgt_conf.remote_session_conf.max_messages_per_second}} + {{device_mgt_conf.remote_session_conf.session_idle_timeout}} + {{device_mgt_conf.remote_session_conf.max_message_buffer.size}} + {% else %} + true + ws://localhost:9763 + 2 + 100 + 20 + 15 + 640 + {% endif %} + + {% if device_mgt_conf.default_groups_conf is defined %} + {{device_mgt_conf.default_groups_conf}} + {% else %} + BYOD,COPE + {% endif %} + + {% if device_mgt_conf.enrolement_notification_conf is defined %} + {{device_mgt_conf.enrolement_notification_conf.enabled}} + {{device_mgt_conf.enrolement_notification_conf.notify_through_extension}} + {{device_mgt_conf.enrolement_notification_conf.extension_class}} + {{device_mgt_conf.enrolement_notification_conf.notify_internal_host}} + {% else %} + false + false + org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifier + http://localhost:8280 + {% endif %} + + + {% if device_mgt_conf.default_roles is defined %} + {{device_mgt_conf.default_roles.enabled}} + {% else %} + false + {% endif %} + + + test_role + + /permission/admin/Login + + + + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 new file mode 100755 index 0000000000..e9105a8d3e --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/cdm-datasources.xml.j2 @@ -0,0 +1,87 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + DM_DS + The datasource used for CDM + + jdbc/DM_DS + + + + {% if database.device_mgt is defined %} + {{database.device_mgt.url}} + {{database.device_mgt.username}} + {{database.device_mgt.password}} + {{database.device_mgt.driver}} + {{database.device_mgt.validationQuery}} + {% for property_name,property_value in database.device_mgt.pool_options.items() %} + <{{property_name}}>{{property_value}} + {% endfor %} + {% else %} + jdbc:h2:./repository/database/WSO2DM_DB;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + {% endif %} + + + + + DM_ARCHIVAL_DS + The archival datasource used for CDM + + jdbc/DM_ARCHIVAL_DS + + + + {% if database.device_mgt_archival is defined %} + {{database.device_mgt_archival.url}} + {{database.device_mgt_archival.username}} + {{database.device_mgt_archival.password}} + {{database.device_mgt_archival.driver}} + {{database.device_mgt_archival.validationQuery}} + {% for property_name,property_value in database.device_mgt_archival.pool_options.items() %} + <{{property_name}}>{{property_value}} + {% endfor %} + {% else %} + jdbc:h2:./repository/database/WSO2DM_ARCHIVAL_DS;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + {% endif %} + + + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/license-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/license-config.xml.j2 new file mode 100644 index 0000000000..ab2e462b42 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/license-config.xml.j2 @@ -0,0 +1,63 @@ + + + + + + + wso2 + android + 1.0.0 + 1.0.0 + 01-01-2014 + 31-12-2035 + + + + wso2 + ios + 1.0.0 + 1.0.0 + 01-01-2014 + 31-12-2035 + + + + wso2 + windows + 1.0.0 + 1.0.0 + 01-01-2014 + 31-12-2035 + + + {% if license_conf.licenses is defined %} + {%- for license in license_conf.licenses -%} + + {{license.provider}} + {{license.name}} + {{license.version}} + {{license.language}} + {{license.valid_from}} + {{license.valid-to}} + {{license.text}} + + {% endfor %} + {% endif %} + + \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/remote-appmanager-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/remote-appmanager-config.xml.j2 new file mode 100644 index 0000000000..5f752a4983 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/etc/remote-appmanager-config.xml.j2 @@ -0,0 +1,32 @@ + + + + + {% if app_management_conf is defined %} + {{app_management_conf.enable}} + {{app_management_conf.app_manager_url}} + {{app_management_conf.consumer_key}} + {{app_management_conf.consumer_secret}} + {% else %} + true + http:/www.google.com + http:/www.google.com + http:/www.google.com + {% endif %} + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 new file mode 100644 index 0000000000..d15f23de86 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 @@ -0,0 +1,211 @@ + + + + + {% if mdm_ui_conf.enable_oauth is defined %} + {{mdm_ui_conf.enable_oauth}} + {% else %} + true + {% endif %} + {% if mdm_ui_conf.enable_sso is defined %} + {{mdm_ui_conf.enable_sso}} + {% else %} + true + {% endif %} + + + application_management + device_management + subscription_management + review_management + {% if mdm_ui_conf.app_registration.tags is defined %} + {%- for tag in mdm_ui_conf.app_registration.tags -%} + {{tag}} + {% endfor %} + {% endif %} + + {% if mdm_ui_conf.app_registration.allow_to_all_domains is defined %} + {{mdm_ui_conf.app_registration.allow_to_all_domains}} + {% else %} + true + {% endif %} + + + perm:app:review:view + perm:app:review:update + perm:app:publisher:view + perm:app:publisher:update + perm:app:store:view + perm:app:subscription:install + perm:app:subscription:uninstall + perm:admin:app:review:update + perm:admin:app:review:view + perm:admin:app:publisher:update + perm:admin:app:review:update + perm:admin:app:subscription:view + perm:device-types:types + perm:enterprise:modify + perm:enterprise:view + perm:android-work:customer + perm:android-work:admin + perm:application-command:modify + perm:sign-csr + perm:admin:devices:view + perm:admin:topics:view + perm:roles:add + perm:roles:add-users + perm:roles:update + perm:roles:permissions + perm:roles:details + perm:roles:view + perm:roles:create-combined-role + perm:roles:delete + perm:dashboard:vulnerabilities + perm:dashboard:non-compliant-count + perm:dashboard:non-compliant + perm:dashboard:by-groups + perm:dashboard:device-counts + perm:dashboard:feature-non-compliant + perm:dashboard:count-overview + perm:dashboard:filtered-count + perm:dashboard:details + perm:get-activity + perm:devices:delete + perm:devices:applications + perm:devices:effective-policy + perm:devices:compliance-data + perm:devices:features + perm:devices:operations + perm:devices:search + perm:devices:details + perm:devices:update + perm:devices:view + perm:view-configuration + perm:manage-configuration + perm:policies:remove + perm:policies:priorities + perm:policies:deactivate + perm:policies:get-policy-details + perm:policies:manage + perm:policies:activate + perm:policies:update + perm:policies:changes + perm:policies:get-details + perm:users:add + perm:users:details + perm:users:count + perm:users:delete + perm:users:roles + perm:users:user-details + perm:users:credentials + perm:users:search + perm:users:is-exist + perm:users:update + perm:users:send-invitation + perm:admin-users:view + perm:admin:devices:update-enrollment + perm:groups:devices + perm:groups:update + perm:groups:add + perm:groups:device + perm:groups:devices-count + perm:groups:remove + perm:groups:groups + perm:groups:groups-view + perm:groups:share + perm:groups:count + perm:groups:roles + perm:groups:devices-remove + perm:groups:devices-add + perm:groups:assign + perm:device-types:configs + perm:device-types:features + perm:device-types:types + perm:applications:install + perm:applications:uninstall + perm:admin-groups:count + perm:admin-groups:view + perm:admin-groups:add + perm:notifications:mark-checked + perm:notifications:view + perm:admin:certificates:delete + perm:admin:certificates:details + perm:admin:certificates:view + perm:admin:certificates:add + perm:admin:certificates:verify + perm:admin + perm:devicetype:deployment + perm:device-types:events + perm:device-types:events:view + perm:admin:device-type + perm:admin:device-type:view + perm:admin:device-type:configs + perm:device:enroll + perm:geo-service:analytics-view + perm:geo-service:alerts-manage + appm:read + perm:devices:permanent-delete + perm:android:manage-configuration + perm:android:view-configuration + perm:user:permission-view + perm:ios:view-configuration + perm:ios:manage-configuration + perm:ios:dep-view + perm:ios:dep-add + perm:windows:view-configuration + perm:windows:manage-configuration + perm:android:lock-devices + perm:android:unlock-devices + perm:android:location + perm:android:clear-password + perm:android:control-camera + perm:android:enterprise-wipe + perm:android:wipe + perm:android:ring + perm:android:applications + perm:android:reboot + perm:android:change-LockTask + perm:android:mute + perm:android:configure-display-message + perm:android:send-app-restrictions + perm:android:file-transfer + perm:android:set-webclip + perm:android:set-password-policy + perm:android:change-lock-code + perm:android:upgrade-firmware + perm:android:send-notification + perm:geo-service:geo-fence + perm:metadata:view + perm:metadata:create + perm:metadata:update + {% if mdm_ui_conf.scopes is defined %} + {%- for scope in mdm_ui_conf.scopes -%} + {{scope}} + {% endfor %} + {% endif %} + + + {% if mdm_ui_conf.sso_conf is defined %} + {{mdm_ui_conf.sso_conf.issuer}} + {% else %} + device-mgt + {% endif %} + + + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf index 09ec420214..5ebad17202 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf @@ -1,4 +1,5 @@ instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/datasources/cdm-datasources.xml,target:${installFolder}/../../conf/datasources/cdm-datasources.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/cdm-config.xml,target:${installFolder}/../../conf/cdm-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/mdm-ui-config.xml,target:${installFolder}/../../conf/mdm-ui-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/license-config.xml,target:${installFolder}/../../conf/etc/license-config.xml,overwrite:true);\ @@ -7,5 +8,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/rxts/license.rxt,target:${installFolder}/../../../repository/resources/rxts/license.rxt,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/email-templates);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/apis/admin--OAuth2TokenManagement.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/admin--OAuth2TokenManagement.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/apis/admin--UserManagementValidateUser.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/admin--UserManagementValidateUser.xml,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml index 3c4216dfb9..d9969b9071 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.extensions.feature/pom.xml @@ -4,14 +4,13 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.extensions.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Management Extensions Feature http://wso2.org This feature contains common extensions used by key device management functionalities @@ -87,8 +86,6 @@ org.wso2.carbon.core.server:${carbon.kernel.version} - org.wso2.carbon.governance.metadata.server:${carbon.governance.version} - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml index 5dcaac8a0f..2b919cccdf 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -39,11 +39,6 @@ org.wso2.carbon.device.mgt.server.feature zip - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.ui.feature - zip - javax.servlet.jsp javax.servlet.jsp-api @@ -80,7 +75,6 @@ org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.server.feature:${carbon.device.mgt.version} - org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.ui.feature:${carbon.device.mgt.version} javax.servlet.jsp:javax.servlet.jsp-api diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index d5d7bf98f0..3e5bc9400e 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Management Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml index e00fa634c8..c4f70cf3be 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.ui.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 28f576bf2e..d53543139b 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml @@ -35,11 +35,9 @@ org.wso2.carbon.device.mgt.basics.feature org.wso2.carbon.device.mgt.server.feature - org.wso2.carbon.device.mgt.ui.feature org.wso2.carbon.device.mgt.api.feature org.wso2.carbon.device.mgt.feature org.wso2.carbon.device.mgt.extensions.feature - org.wso2.carbon.device.mgt.analytics.feature diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml index db6da06d04..ceae78d430 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt heart-beat-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml @@ -73,14 +73,6 @@ org.codehaus.woodstox wstx-asl - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - - - org.wso2.carbon.analytics - org.wso2.carbon.analytics.api - diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 new file mode 100644 index 0000000000..524f28c42a --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/datasources/heart-beat-datasources.xml.j2 @@ -0,0 +1,57 @@ + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + HeartBeat_DS + The datasource Server Heart Beat + + jdbc/HeartBeat_DS + + + + {% if database.heart_beat is defined %} + {{database.heart_beat.url}} + {{database.heart_beat.username}} + {{database.heart_beat.password}} + {{database.heart_beat.driver}} + {{database.heart_beat.validationQuery}} + {% for property_name,property_value in database.heart_beat.pool_options.items() %} + <{{property_name}}>{{property_value}} + {% endfor %} + {% else %} + jdbc:mysql://localhost:3306/heart_beat + root + root + com.mysql.jdbc.Driver + 50 + 60000 + true + SELECT 1 + 30000 + {% endif %} + + + + + + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 new file mode 100644 index 0000000000..8d2776fc38 --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf_templates/templates/repository/conf/heart-beat-config.xml.j2 @@ -0,0 +1,61 @@ + + + + + + + + + jdbc/HeartBeat_DS + + + {% if heart_beat_beacon_conf is defined %} + {{heart_beat_beacon_conf.enable}} + {{heart_beat_beacon_conf.notifier_initial_delay_in_seconds}} + {{heart_beat_beacon_conf.notifier_frequency_in_seconds}} + {{heart_beat_beacon_conf.time_skew_in_seconds}} + {{heart_beat_beacon_conf.sever_timeout_interval_in_seconds}} + {% else %} + false + 30 + 300 + 5 + 600 + {% endif %} + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf index 6add373677..55584ad49a 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf @@ -2,6 +2,7 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/conf/heart-beat-config.xml,target:${installFolder}/../../conf/heart-beat-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/dbscripts/heart-beat/,target:${installFolder}/../../../dbscripts/heart-beat,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ instructions.unconfigure = \ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/heart-beat-datasources.xml);\ diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 2602548044..b034331e1b 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt heart-beat-feature - 4.1.16-SNAPSHOT pom Entgra - Heart Beat Feature http://entgra.io diff --git a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml index 410cca6e21..4047e2295c 100644 --- a/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/org.wso2.carbon.identity.jwt.client.extension.feature/pom.xml @@ -23,14 +23,13 @@ org.wso2.carbon.devicemgt jwt-client-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.identity.jwt.client.extension.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - JWT Client Feature http://wso2.org This feature contains jwt client implementation from which we can get a access token using the jwt diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index 75942261f7..994c462f6a 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,13 +23,12 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 jwt-client-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - JWT Client Extension Feature http://wso2.org diff --git a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml index 1ca77e930c..bd943afb33 100644 --- a/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml +++ b/features/oauth-extensions/org.wso2.carbon.device.mgt.oauth.extensions.feature/pom.xml @@ -23,14 +23,13 @@ org.wso2.carbon.devicemgt oauth-extensions-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.oauth.extensions.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Device Mgt OAuth Extensions Feature http://wso2.org This feature contains devicemgt related OAuth extensions diff --git a/features/oauth-extensions/pom.xml b/features/oauth-extensions/pom.xml index 8e62605ea5..5e1d9ad26d 100644 --- a/features/oauth-extensions/pom.xml +++ b/features/oauth-extensions/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt oauth-extensions-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Device Management OAuth Extensions Feature http://wso2.org diff --git a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml index daffbc913c..57146156f9 100644 --- a/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/org.wso2.carbon.policy.mgt.server.feature/pom.xml @@ -23,14 +23,13 @@ org.wso2.carbon.devicemgt policy-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.policy.mgt.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Policy Management Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index 3223326c5c..44dd54475a 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,14 +23,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt policy-mgt-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Policy Management Feature http://wso2.org diff --git a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml index eaf13f69ff..52a2cc4730 100644 --- a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt email-sender-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.email.sender.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Email Sender Feature http://wso2.org This feature contains the core bundles required for email sender related functionality diff --git a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf_templates/templates/repository/conf/etc/email-sender-config.xml.j2 b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf_templates/templates/repository/conf/etc/email-sender-config.xml.j2 new file mode 100644 index 0000000000..f59e8fbf53 --- /dev/null +++ b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf_templates/templates/repository/conf/etc/email-sender-config.xml.j2 @@ -0,0 +1,38 @@ + + + + {% if email_sender_conf is defined %} + {{email_sender_conf.min_threads}} + + {{email_sender_conf.max_threads}} + + {{email_sender_conf.keep_alive_duration}} + + {{email_sender_conf.thread_queue_capacity}} + {% else %} + 8 + + 100 + + 20 + + 1000 + {% endif %} + + diff --git a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf index d4dadf6a1e..03d6cc09f9 100644 --- a/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf +++ b/features/transport-mgt/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf @@ -1,3 +1,4 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/conf/email-sender-config.xml,target:${installFolder}/../../conf/etc/email-sender-config.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index 3292c9ddd4..f44b2990b2 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt transport-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.devicemgt email-sender-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Email Sender Feature http://wso2.org diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index 1ad1049576..7f934bdd60 100644 --- a/features/transport-mgt/pom.xml +++ b/features/transport-mgt/pom.xml @@ -3,7 +3,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml index 9c33be06bb..a702d27095 100644 --- a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.api.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt sms-handler-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 io.entgra.transport.mgt.sms.handler.api.feature pom - 4.1.16-SNAPSHOT Entgra - SMS Handler API Feature https://entgra.io This feature contains the APIs required for SMS Handler diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml index e6555c2037..9fad844781 100644 --- a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt sms-handler-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 io.entgra.transport.mgt.sms.handler.server.feature pom - 4.1.16-SNAPSHOT Entgra - SMS Handler Server Feature https://entgra.io This feature contains the core bundles required for Back-end SMS Handler functionality diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/conf_templates/templates/repository/conf/sms-config.xml.j2 b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/conf_templates/templates/repository/conf/sms-config.xml.j2 new file mode 100644 index 0000000000..0ffc635427 --- /dev/null +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/conf_templates/templates/repository/conf/sms-config.xml.j2 @@ -0,0 +1,45 @@ + + + + + + + + + + + sample + +94 + 160 + + + {% if sms_conf.gateways is defined %} + {%- for gateway in sms_conf.gateways -%} + + + {% for property_name,property_value in gateway.properties_options.items() %} + {{property_value}} + {% endfor %} + + + {% endfor %} + {% endif %} + + diff --git a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/p2.inf b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/p2.inf index af486db59b..958e75d3ab 100644 --- a/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/p2.inf +++ b/features/transport-mgt/sms-handler/io.entgra.transport.mgt.sms.handler.server.feature/src/main/resources/p2.inf @@ -1,4 +1,5 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.transport.mgt.sms.handler.server_${feature.version}/conf/sms-config.xml,target:${installFolder}/../../conf/sms-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.transport.mgt.sms.handler.server_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ instructions.unconfigure = \ diff --git a/features/transport-mgt/sms-handler/pom.xml b/features/transport-mgt/sms-handler/pom.xml index d5bf4be703..107357cbaf 100644 --- a/features/transport-mgt/sms-handler/pom.xml +++ b/features/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt transport-mgt-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml index b1df7b1684..364ce6a9f4 100644 --- a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor-feature io.entgra.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT 4.0.0 diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf index 7887868228..d44e4112ef 100644 --- a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/p2.inf @@ -4,3 +4,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/store-ui-request-handler.war,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/entgra-ui-request-handler.war,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/webapps/ui-request-handler.war,target:${installFolder}/../../deployment/server/webapps/mdm-reports-ui-request-handler.war,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.ui.request.interceptor_${feature.version}/payloads/,target:${installFolder}/../../resources/payloads/,overwrite:true);\ diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/get-app-request.xml b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/get-app-request.xml new file mode 100644 index 0000000000..45c2042031 --- /dev/null +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/get-app-request.xml @@ -0,0 +1,8 @@ + + + + + ${applicationName} + + + diff --git a/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/update-app-request.xml b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/update-app-request.xml new file mode 100644 index 0000000000..50e82b986c --- /dev/null +++ b/features/ui-request-interceptor/io.entgra.ui.request.interceptor.feature/src/main/resources/payloads/update-app-request.xml @@ -0,0 +1,97 @@ + + + + + + + ${applicationId} + ${applicationName} + + ${description} + + + + + + + + + + + + + http://wso2.org/claims/username + + + true + + + + + + http://testclaims/claims/username + + + true + + + + + + + + + + + + + + + + + + + + + ${inboundAuthKey} + ${inboundAuthType} + ${inboundConfigType} + + + + + + ${tenantDomain} + ${userName} + ${userStoreDomain} + + ${saasApp} + + + displayName + ${displayName} + + + + + + + diff --git a/features/ui-request-interceptor/pom.xml b/features/ui-request-interceptor/pom.xml index 0ab46ec416..1e4441c810 100644 --- a/features/ui-request-interceptor/pom.xml +++ b/features/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml index a2448e6fff..7f825735f1 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt webapp-authenticator-framework-feature - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.webapp.authenticator.framework.server.feature pom - 4.1.16-SNAPSHOT WSO2 Carbon - Webapp Authenticator Framework Server Feature http://wso2.org This feature contains the core bundles required for Back-end Device Management functionality diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-authenticator-config.xml.j2 b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-authenticator-config.xml.j2 new file mode 100644 index 0000000000..187c9131fe --- /dev/null +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/conf_templates/templates/repository/conf/etc/webapp-authenticator-config.xml.j2 @@ -0,0 +1,118 @@ + + + + OAuth + {% if webapp_auth_conf.authenticator.oauth is defined %} + {{webapp_auth_conf.authenticator.oauth.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.oauth.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator + + false + https://${iot.keymanager.host}:${iot.keymanager.https.port} + admin + admin + 100 + 100 + + {% endif %} + + + BasicAuth + {% if webapp_auth_conf.authenticator.basic_auth is defined %} + {{webapp_auth_conf.authenticator.basic_auth.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.basic_auth.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator + {% endif %} + + + JWT + {% if webapp_auth_conf.authenticator.jwt is defined %} + {{webapp_auth_conf.authenticator.jwt.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.jwt.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator + + + wso2carbon + wso2carbon + wso2carbon + wso2carbon + + {% endif %} + + + CertificateAuth + {% if webapp_auth_conf.authenticator.certificate_auth is defined %} + {{webapp_auth_conf.authenticator.certificate_auth.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.certificate_auth.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.CertificateAuthenticator + {% endif %} + + + OTPAuth + {% if webapp_auth_conf.authenticator.otpauth is defined %} + {{webapp_auth_conf.authenticator.otpauth.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.otpauth.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.OneTimeTokenAuthenticator + {% endif %} + + + BST + {% if webapp_auth_conf.authenticator.bst is defined %} + {{webapp_auth_conf.authenticator.bst.class_name}} + + {% for property_name,property_value in webapp_auth_conf.authenticator.bst.parameter_options.items() %} + {{property_value}} + {% endfor %} + + {% else %} + org.wso2.carbon.webapp.authenticator.framework.authenticator.BSTAuthenticator + + false + https://${iot.keymanager.host}:${iot.keymanager.https.port} + admin + admin + 100 + 100 + + {% endif %} + + {% if webapp_auth_conf.authenticators is defined %} + {%- for authenticator in webapp_auth_conf.authenticators -%} + + {{authenticator.name}} + {{authenticator.class_name}} + + {% for property_name,property_value in authenticator.parameter_options.items() %} + {{property_value}} + {% endfor %} + + + {% endfor %} + {% endif %} + + diff --git a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/p2.inf b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/p2.inf index 7b1ad15df1..a526d71269 100644 --- a/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/p2.inf +++ b/features/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework.server.feature/src/main/resources/p2.inf @@ -1,2 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.webapp.authenticator.framework.server_${feature.version}/conf/webapp-authenticator-config.xml,target:${installFolder}/../../conf/etc/webapp-authenticator-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.webapp.authenticator.framework.server_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index 264f071c9d..d399ea4680 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,14 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt webapp-authenticator-framework-feature - 4.1.16-SNAPSHOT pom WSO2 Carbon - Webapp Authenticator Framework Feature http://wso2.org diff --git a/pom.xml b/pom.xml index 39f8ff4e85..ea11339d6e 100644 --- a/pom.xml +++ b/pom.xml @@ -23,11 +23,10 @@ org.wso2.carbon.devicemgt carbon-devicemgt pom - 4.1.16-SNAPSHOT + 5.0.0-SNAPSHOT WSO2 Carbon - Device Management - Parent http://wso2.org WSO2 Connected Device Manager Components - org.wso2 wso2 @@ -43,21 +42,20 @@ components/application-mgt components/policy-mgt components/certificate-mgt - components/webapp-authenticator-framework components/ui-request-interceptor components/transport-mgt + components/webapp-authenticator-framework features/device-mgt features/apimgt-extensions features/application-mgt features/policy-mgt - features/webapp-authenticator-framework features/certificate-mgt - features/oauth-extensions features/heartbeat-management features/ui-request-interceptor features/jwt-client features/device-mgt-extensions features/transport-mgt + features/webapp-authenticator-framework @@ -225,11 +223,6 @@ org.wso2.carbon.policy.mgt.core ${carbon.device.mgt.version} - - org.wso2.carbon.devicemgt - org.wso2.carbon.complex.policy.decision.point - ${carbon.device.mgt.version} - org.wso2.carbon.devicemgt org.wso2.carbon.policy.decision.point @@ -245,16 +238,6 @@ org.wso2.carbon.apimgt.webapp.publisher ${carbon.device.mgt.version} - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.client - ${carbon.device.mgt.version} - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.integration.generated.client - ${carbon.device.mgt.version} - org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations @@ -286,11 +269,6 @@ org.wso2.carbon.device.mgt.analytics.data.publisher ${carbon.device.mgt.version} - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.wsproxy - ${carbon.device.mgt.version} - org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.server.feature @@ -309,12 +287,6 @@ zip ${carbon.device.mgt.version} - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.ui.feature - zip - ${carbon.device.mgt.version} - org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.application.extension @@ -330,12 +302,6 @@ org.wso2.carbon.apimgt.application.extension.api ${carbon.device.mgt.version} - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.handlers - ${carbon.device.mgt.version} - org.wso2.carbon.devicemgt org.wso2.carbon.device.application.mgt.server.feature @@ -483,7 +449,8 @@ javax.servlet - javax.servlet-api + javax.servlet-api + @@ -696,10 +663,6 @@ commons-httpclient.wso2 commons-httpclient - - commons-httpclient.wso2 - commons-httpclient - org.wso2.carbon org.wso2.carbon.registry.api @@ -832,7 +795,7 @@ org.wso2.carbon org.wso2.carbon.logging - ${carbon.kernel.version} + ${org.wso2.carbon.logging.version} org.wso2.carbon @@ -908,7 +871,12 @@ org.wso2.carbon.apimgt - org.wso2.carbon.apimgt.keymgt + org.wso2.carbon.apimgt.api + ${carbon.api.mgt.version} + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl ${carbon.api.mgt.version} @@ -1153,17 +1121,6 @@ - - org.apache.cxf - cxf-rt-bindings-http - ${cxf.bindings.version} - - - org.codehaus.jra - jra - - - org.apache.cxf cxf-rt-rs-extension-providers @@ -1794,6 +1751,16 @@ commons-validator ${apache.validator.version} + + org.springframework + spring-web + ${spring-web.version} + + + org.apache.cxf + cxf-bundle-jaxrs + ${cxf-bundle-package.version} + @@ -2054,11 +2021,12 @@ 2.2.1 6.1.1 - 4.4.26 - [4.4.0, 5.0.0) - 1.5.4 + 4.6.2 + [4.5.0, 5.0.0) + 5.1.2 1.3 3.1.3 + 4.4.9 [1.6.1.wso2v11, 1.7.0) @@ -2082,9 +2050,9 @@ 4.8.2 - 3.6.100.v20120522-1841 + 3.6.200.v20130402-1505 3.3.100.v20120522-1822 - 3.9.1.v20130814-1242 + 3.9.1.v20140110-1610 1.2.140.wso2v3 @@ -2097,22 +2065,22 @@ 4.7.15 - 5.11.148 - [5.2.0, 6.0.0) - 5.6.63 - 5.4.6 - 1.0.10 - [1.0.10, 2.0.0) + 5.18.187 + [5.2.0, 7.0.0) + 6.4.111 + 5.5.2 + 1.0.31 + [1.0.31, 2.0.0) - [5.7.0, 6.0.0) - [5.2.0, 6.0.0) - [5.1.0, 6.0.0) + [5.14.0, 6.0.0) + [6.0.0, 7.0.0) + [5.3.0, 6.0.0) - 4.6.11 + 4.9.10 - 4.7.23 + 4.8.21 1.2.11-wso2v10 @@ -2120,10 +2088,10 @@ 1.2.11.wso2v10 - 4.1.16-SNAPSHOT + ${project.version} - 4.6.21 + 4.7.35 1.4.0.wso2v1 [1.4.0,2.0.0) 2.4.0.wso2v1 @@ -2131,8 +2099,8 @@ [2.6.0,3.0.0) - 6.2.201 - (6.0.0,7.0.0] + 9.0.174 + [9.0.0, 10.0.0) 5.1.37 @@ -2142,31 +2110,28 @@ 2.1.23 - 4.6.28 - 4.6.8 - [4.4.8, 5.0.0) + 4.7.39 + ${carbon.registry.version} + [4.7.0, 5.0.0) - 3.2.0 - 2.5.11 + 3.3.6 + 1.1.wso2v1 1.9.0 - 1.52.0.wso2v1 - 1.52.0.wso2v2 - [1.52.0,1.60.0) + 1.60.0.wso2v1 + 1.60.0.wso2v1 + [1.52.0,1.70.0) 2.3.0.wso2v2 - - 2.26.1.wso2v3 - 3.0.0.wso2v1 1.3 - 2.3.1 - 3.8.1 + 2.8.5 + 4.6.0 1.13.0 9.3.1 1.1.1 @@ -2216,12 +2181,12 @@ 2.0.1 1.5.10 - 1.5.10 + 1.6.1 4.0.1 1.0.10 - 2.6.1.wso2v1 + 2.9.8.wso2v1 2.6.1.wso2v3 2.8.2.wso2v1 1.2.0.wso2v1 @@ -2245,7 +2210,7 @@ 1.7 - 2.1.7-wso2v7 + 2.1.7-wso2v227 1.5.11.wso2v15 @@ -2282,6 +2247,14 @@ 7.0.85 1.0 1.13.1 + + 5.1.13.RELEASE + 2.7.18 + + [1.6.0, 2.0.0) + [1.2.0,1.3.0) + + true