diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml index 2d8a1dc40c..23bb4eece2 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml index a759665e92..4839960ae1 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml index ce25a77c31..0c336eadda 100644 --- a/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml +++ b/components/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml @@ -189,8 +189,8 @@ compile - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 io.entgra.device.mgt.core diff --git a/components/analytics-mgt/grafana-mgt/pom.xml b/components/analytics-mgt/grafana-mgt/pom.xml index 7bc9db7e86..1e498a9cbd 100644 --- a/components/analytics-mgt/grafana-mgt/pom.xml +++ b/components/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml index bc9ce9529f..320c3bd644 100644 --- a/components/analytics-mgt/pom.xml +++ b/components/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml index 951f3813a2..d5195bca96 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml @@ -20,7 +20,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml index 8fc927f575..eb33dc54e7 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.annotations/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml index 00bad68142..c3ff3a43e8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index 8083f332bc..2dd6e523f0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -64,7 +64,8 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, APIUtil.getDefaultTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false, - ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD); + ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } catch (APIManagerException e) { String msg = "Error occurred while registering an application '" + applicationName + "'"; @@ -110,7 +111,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, - registrationProfile.isAllowedToAllDomains(), validityPeriod); + registrationProfile.isAllowedToAllDomains(), validityPeriod, + registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(), + registrationProfile.getCallbackUrl(), false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } } @@ -122,7 +125,9 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( applicationName, registrationProfile.getTags(), ApiApplicationConstants.DEFAULT_TOKEN_TYPE, registrationProfile.getUsername(), - registrationProfile.isAllowedToAllDomains(), validityPeriod); + registrationProfile.isAllowedToAllDomains(), validityPeriod, + registrationProfile.getPassword(), null, registrationProfile.getSupportedGrantTypes(), + registrationProfile.getCallbackUrl(), false); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); } } catch (APIManagerException e) { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java index 3e3eb30a03..921b27f434 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/api/util/RegistrationProfile.java @@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; /** * DTO class to be used when registering an ApiM application. @@ -43,6 +44,10 @@ public class RegistrationProfile { @XmlElement(required = false) private String validityPeriod; + private String callbackUrl; + + private ArrayList supportedGrantTypes; + public String getApplicationName() { return applicationName; } @@ -90,4 +95,20 @@ public class RegistrationProfile { public void setPassword(String password) { this.password = password; } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml index 6f278017d0..f5b8cc9bda 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml @@ -79,6 +79,17 @@ io.entgra.device.mgt.core.identity.jwt.client.extension provided + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.apimgt.extension.rest.api + + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.common + + + @@ -119,11 +130,13 @@ io.entgra.device.mgt.core.identity.jwt.client.extension.dto;version="[5.0,6)", io.entgra.device.mgt.core.identity.jwt.client.extension.exception;version="[5.0,6)", io.entgra.device.mgt.core.identity.jwt.client.extension.service;version="[5.0,6)", + io.entgra.device.mgt.core.device.mgt.common;version="[5.0,6)", org.apache.commons.lang;version="[2.6,3)", org.apache.commons.logging;version="[1.2,2)", org.json.simple;version="[1.1,2)", org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.service.*;version="${imp.package.version.osgi.service}", + io.entgra.device.mgt.core.apimgt.extension.rest.api, org.wso2.carbon.apimgt.api;version="[9.28,10)", org.wso2.carbon.apimgt.api.dto;version="[9.28,10)", org.wso2.carbon.apimgt.api.model;version="[9.28,10)", diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java index a46dc715b7..589923a920 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderService.java @@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplication import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; +import java.util.ArrayList; + /** * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM. */ @@ -33,27 +35,14 @@ public interface APIManagementProviderService { */ boolean isTierLoaded(); - /** - * 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 - * @return consumerkey and secrete of the created application. - * @throws APIManagerException - */ - ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[], - String keyType, String username, boolean isAllowedAllDomains, - String validityTime) throws APIManagerException; - - /** - * Remove APIM Application. - */ - void removeAPIApplication(String applicationName, String username) throws APIManagerException; + ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, + String keyType, String username, + boolean isAllowedAllDomains, + String validityTime, + String password, String accessToken, + ArrayList supportedGrantTypes, + String callbackUrl, + boolean isMappingRequired) throws APIManagerException; /** * To get access token for given scopes and for the given validity period diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java index 86d11670a1..837a1b902c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -19,24 +19,32 @@ package io.entgra.device.mgt.core.apimgt.application.extension; import io.entgra.device.mgt.core.apimgt.application.extension.bean.APIRegistrationProfile; -import io.entgra.device.mgt.core.apimgt.application.extension.constants.ApiApplicationConstants; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; -import io.entgra.device.mgt.core.apimgt.application.extension.util.APIManagerUtil; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.APIInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.ApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.KeyManager; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Subscription; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.identity.jwt.client.extension.JWTClient; import io.entgra.device.mgt.core.identity.jwt.client.extension.dto.AccessTokenInfo; import io.entgra.device.mgt.core.identity.jwt.client.extension.exception.JWTClientException; import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; 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.*; -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; @@ -44,7 +52,13 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; /** * This class represents an implementation of APIManagementProviderService. @@ -53,6 +67,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); + private static final String UNLIMITED_TIER = "Unlimited"; @Override public boolean isTierLoaded() { @@ -70,222 +85,235 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } @Override - public void removeAPIApplication(String applicationName, String username) throws APIManagerException { + public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, + String keyType, String username, + boolean isAllowedAllDomains, + String validityTime, + String password, String accessToken, + ArrayList supportedGrantTypes, + String callbackUrl, + boolean isMappingRequired) + throws APIManagerException { - try { - APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); - Application application = null; // todo:apim - apiConsumer.getApplicationsByName(username, applicationName, ""); - if (application != null) { - // todo:apim - apiConsumer.removeApplication(application, username); - } - } catch (APIManagementException e) { - throw new APIManagerException("Failed to remove api application : " + applicationName, e); + ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo(); + if (StringUtils.isEmpty(accessToken)) { + apiApplicationInfo = getApplicationInfo(username, password); + } else { + apiApplicationInfo.setAccess_token(accessToken); } + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], - String keyType, String username, boolean isAllowedAllDomains, String validityTime) - throws APIManagerException { - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (StringUtils.isEmpty(username)) { - username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername() + "@" + tenantDomain; - } try { - APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username); - Application application = null; // todo:apim - apiConsumer.getApplicationsByName(username, applicationName, ""); - - int applicationId = 0; - Subscriber subscriber = null; - if (application == null) { - subscriber = null; // todo:apim - apiConsumer.getSubscriber(username); - if (subscriber == null) { - // create subscriber - // todo:apim - apiConsumer.addSubscriber(username, ""); - subscriber = null; // todo:apim - apiConsumer.getSubscriber(username); - } - //create application - application = new Application(applicationName, subscriber); - application.setTier(ApiApplicationConstants.DEFAULT_TIER); - application.setGroupId(""); - application.setTokenType("OAUTH"); - // todo:apim - apiConsumer.addApplication(application, username); - application = null; // todo:apim - apiConsumer.getApplicationsByName(username, applicationName, ""); - } else { - subscriber = null; // todo:apim - apiConsumer.getSubscriber(username); + Map headerParams = new HashMap<>(); + if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) { + headerParams.put("X-WSO2-Tenant", "carbon.super"); } - Set subscribedAPIs = - null; // todo:apim - apiConsumer.getSubscribedAPIs(subscriber, applicationName, ""); - - log.info("Already subscribed API count: " + subscribedAPIs.size()); - - // subscribe to apis. - Set tempApiIds = new HashSet<>(); - APIConsumer apiConsumerAPIPublishedTenant = apiConsumer; - if (tags != null && tags.length > 0) { - for (String tag : tags) { - boolean startedTenantFlow = false; - Set apisWithTag = null; // todo:apim - apiConsumer.getAPIsWithTag(tag, tenantDomain); - - /** - * From APIM 4.0.0, APIs published in the super tenant can only be listed by - * APIConsumer, only if the APIConsumer belongs to the super tenant. So we - * are starting tenant flow if we are not already in super tenant(child - * tenant starting to create OAuth app). - */ - if (apisWithTag == null || apisWithTag.size() == 0) { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, - true); - - try { - String superAdminUsername = PrivilegedCarbonContext - .getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName(); - apiConsumerAPIPublishedTenant = API_MANAGER_FACTORY.getAPIConsumer(superAdminUsername); - } catch (UserStoreException e) { - throw new APIManagerException("Failed to create api application for " + - "tenant: " + tenantDomain + - ". Caused by to inability to get super tenant username", e); - } + Map uniqueApiSet = new HashMap<>(); + for (String tag : tags) { + Map queryParams = new HashMap<>(); + queryParams.put("tag", tag); - apisWithTag = null; // todo:apim - apiConsumerAPIPublishedTenant.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - startedTenantFlow = true; - } + APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(apiApplicationInfo, queryParams, headerParams); + Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo)); + } - Set apiTypeWrapperList = new HashSet<>(); - if (apisWithTag != null && apisWithTag.size() > 0) { - for (API apiInfo : apisWithTag) { - String id = apiInfo.getId().getProviderName().replace("@", "-AT-") - + "-" + apiInfo.getId().getName() + "-" + apiInfo.getId().getVersion(); - boolean subscriptionExist = false; - if (subscribedAPIs.size() > 0) { - for (SubscribedAPI subscribedAPI : subscribedAPIs) { - // todo:apim -// if (String.valueOf(subscribedAPI.getApiId().toString()).equals(id)) { -// subscriptionExist = true; -// break; -// } - } - } - if (!subscriptionExist && !tempApiIds.contains(id)) { - ApiTypeWrapper apiTypeWrapper; - if (startedTenantFlow) { - /** - * This mean APIs were not found in the child tenant, so all - * calls to get info about APIs need to be to super tenant. - */ - apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID( - apiInfo.getUuid(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - } else { - /** - * Ideally, in all usecases of IoT server, tenant domain here - * will be carbon.super. This block is kept to make sure in - * the future, if there are some APIs published to a specific - * tenant only. - */ - apiTypeWrapper = apiConsumerAPIPublishedTenant.getAPIorAPIProductByUUID( - apiInfo.getUuid(), tenantDomain); - } - apiTypeWrapper.setTier(ApiApplicationConstants.DEFAULT_TIER); - apiTypeWrapperList.add(apiTypeWrapper); - tempApiIds.add(id); - } - } - if (startedTenantFlow) { - PrivilegedCarbonContext.endTenantFlow(); + List uniqueApiList = new ArrayList<>(uniqueApiSet.values()); + + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = + consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName); + if (applications.length == 0) { + return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType, + validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); + } else { + if (applications.length == 1) { + Optional applicationOpt = + Arrays.stream(applications).findFirst(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = + applicationOpt.get(); + + MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); + Metadata metaData = metadataManagementService.retrieveMetadata(applicationName); + if (metaData == null) { + // Todo add a comment + consumerRESTAPIServices.deleteApplication(apiApplicationInfo, application.getApplicationId()); + return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType, + validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); + } else { + Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(apiApplicationInfo, application.getApplicationId()); + for (Subscription subscription : subscriptions) { + uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId())); } - /** This is done in a redundant loop instead of doing in the same loop - * that populates apiTypeWrapperList because in a tenanted scenario, - * apiConsumerAPIPublishedTenant will belong to super tenant. So super - * tenant flow need to end before starting subscription to avoid adding - * subscriptions inside super tenant when we are trying to create an - * Oauth app for a child tenant. - */ - for (ApiTypeWrapper apiTypeWrapper : apiTypeWrapperList) { - // todo:apim - apiConsumer.addSubscription(apiTypeWrapper, username, application); + if (!uniqueApiList.isEmpty()) { + addSubscriptions(application, uniqueApiList, apiApplicationInfo); } - } - } - } - //end of subscription - - List applicationKeys = application.getKeys(); - if (applicationKeys != null) { - for (APIKey applicationKey : applicationKeys) { - if (keyType.equals(applicationKey.getType())) { - if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { - ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); - apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); - apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); - return apiApplicationKey; + + String[] metaValues = metaData.getMetaValue().split(":"); + if (metaValues.length != 2) { + String msg = "Found invalid Meta value for meta key: " + applicationName + ". Meta Value: " + + metaData.getMetaValue(); + log.error(msg); + throw new APIManagerException(msg); } + String applicationId = metaValues[0]; + String keyMappingId = metaValues[1]; + ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(apiApplicationInfo, applicationId, keyMappingId); + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + return apiApplicationKey; } + } else { + String msg = "Found more than one application for application name: " + applicationName; + log.error(msg); + throw new APIManagerException(msg); } } + } catch (APIServicesException e) { + String msg = "Error occurred while processing the response of APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (BadRequestException e) { + String msg = "Provided incorrect payload when invoking APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (UnexpectedResponseException e) { + String msg = "Error occurred while invoking APIM REST endpoints."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (MetadataManagementException e) { + String msg = "Error occurred while getting meta data for meta key: " + applicationName; + log.error(msg, e); + throw new APIManagerException(msg, e); + } + } + + + private ApiApplicationKey handleNewAPIApplication(String applicationName, List uniqueApiList, + ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime, + ArrayList supportedGrantTypes, String callbackUrl, + boolean isMappingRequired) throws APIManagerException { + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = new io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application(); + application.setName(applicationName); + application.setThrottlingPolicy(UNLIMITED_TIER); - List allowedDomains = new ArrayList<>(); - if (isAllowedAllDomains) { - allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); + try { + application = consumerRESTAPIServices.createApplication(apiApplicationInfo, application); + addSubscriptions(application, uniqueApiList, apiApplicationInfo); + + KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(apiApplicationInfo); + KeyManager keyManager; + if (keyManagers.length == 1) { + keyManager = keyManagers[0]; } else { - allowedDomains.add(APIManagerUtil.getTenantDomain()); + String msg = + "Found invalid number of key managers. No of key managers found from the APIM: " + keyManagers.length; + log.error(msg); + throw new APIManagerException(msg); } - APIAdmin apiAdmin = new APIAdminImpl(); - String keyManagerId = null; - try { - List keyManagerConfigurations = null; // todo:apim - apiAdmin -// .getKeyManagerConfigurationsByTenant(tenantDomain); - if (keyManagerConfigurations != null) { - for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurations) { - keyManagerId = keyManagerConfigurationDTO.getUuid(); - } - } - String applicationAccessTokenExpiryTime = "N/A"; - if (!StringUtils.isEmpty(validityTime)) { - applicationAccessTokenExpiryTime = validityTime; - } - String jsonString = "{\"grant_types\":\"refresh_token,access_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\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," + - "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," + - "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + - "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + - "\"username\":\"" + username + "\"}"; - - Map keyDetails = null; // todo:apim - 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); -// todo:apim - commected as it says never throw since we commented apim calls above -// } catch (APIManagementException e) { - } catch (Exception e) { - throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); + ApplicationKey applicationKey; + + if (isMappingRequired) { + // If we need to get opaque token instead of the JWT token, we have to do the mapping. Therefore, if + // it is a requirement then we have to call the method with enabling the flag. + APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance() + .getApiApplicationServices(); + + APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForMapping", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + + apiApplicationInfo.setClientId(apiApplicationKey.getClientId()); + apiApplicationInfo.setClientSecret(apiApplicationKey.getClientSecret()); + + applicationKey = consumerRESTAPIServices.mapApplicationKeys(apiApplicationInfo, application, + keyManager.getName(), keyType); + } else { + applicationKey = consumerRESTAPIServices.generateApplicationKeys(apiApplicationInfo, application.getApplicationId(), + keyManager.getName(), validityTime, keyType); } - } catch (APIManagementException e) { - throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); + if (supportedGrantTypes != null || StringUtils.isNotEmpty(callbackUrl)) { + applicationKey = consumerRESTAPIServices.updateGrantType(apiApplicationInfo, application.getApplicationId(), + applicationKey.getKeyMappingId(), keyManager.getName(), supportedGrantTypes, callbackUrl); + } + + ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); + apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); + apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); + + Metadata metaData = new Metadata(); + metaData.setMetaKey(applicationName); + String metaValue = application.getApplicationId() + ":" + applicationKey.getKeyMappingId(); + metaData.setMetaValue(metaValue); + + MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); + metadataManagementService.createMetadata(metaData); + return apiApplicationKey; + } catch (MetadataManagementException e) { + String msg = "Error occurred while creating meta data for meta key: " + applicationName; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (MetadataKeyAlreadyExistsException e) { + String msg = + "Since meta key:" + applicationName + " already exists, meta data creating process " + + "failed."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (BadRequestException e) { + String msg = "Provided incorrect payload when invoking APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (UnexpectedResponseException e) { + String msg = "Error occurred while invoking APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); + } catch (APIServicesException e) { + String msg = "Error occurred while processing the response of APIM REST endpoints to handle new API application."; + log.error(msg, e); + throw new APIManagerException(msg, e); } } + /** + * This method can be used to add a new subscriptions providing the ids of the APIs and the applications. + * + * @param application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application} + * @param apiInfos {@link List} + * @param apiApplicationInfo {@link ApiApplicationInfo} + * @throws BadRequestException if incorrect data provided to call subscribing REST API. + * @throws UnexpectedResponseException if error occurred while processing the subscribing REST API. + * @throws APIServicesException if error occurred while invoking the subscribing REST API. + */ + private void addSubscriptions( + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application, + List apiInfos, ApiApplicationInfo apiApplicationInfo) + throws BadRequestException, UnexpectedResponseException, APIServicesException { + + ConsumerRESTAPIServices consumerRESTAPIServices = + APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices(); + + List subscriptionList = new ArrayList<>(); + apiInfos.forEach(apiInfo -> { + Subscription subscription = new Subscription(); + subscription.setApiId(apiInfo.getId()); + subscription.setApplicationId(application.getApplicationId()); + subscription.setThrottlingPolicy(UNLIMITED_TIER); + subscription.setRequestedThrottlingPolicy(UNLIMITED_TIER); + subscriptionList.add(subscription); + }); + + consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, subscriptionList); + } + @Override public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, - String validityPeriod, String username) throws APIManagerException { + String validityPeriod, String username) throws APIManagerException { try { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); ApiApplicationKey clientCredentials = getClientCredentials(tenantDomain, tags, applicationName, tokenType, @@ -311,11 +339,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe JWTClientManagerService jwtClientManagerService = APIApplicationManagerExtensionDataHolder.getInstance() .getJwtClientManagerService(); JWTClient jwtClient = jwtClientManagerService.getJWTClient(); - AccessTokenInfo accessTokenForAdmin = jwtClient + + return jwtClient .getAccessToken(clientCredentials.getConsumerKey(), clientCredentials.getConsumerSecret(), username, scopes); - - return accessTokenForAdmin; } catch (JWTClientException e) { String msg = "JWT Error occurred while registering Application to get access token."; log.error(msg, e); @@ -332,18 +359,19 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } /** - * Get Client credentials - * @param tenantDomain Tenant Domain - * @param tags Tags + * Get Client credentials of application belongs to tenant admin + * + * @param tenantDomain Tenant Domain + * @param tags Tags * @param applicationName Application Name - * @param tokenType Token Type - * @param validityPeriod Validity Period + * @param tokenType Token Type + * @param validityPeriod Validity Period * @return {@link ApiApplicationKey} * @throws APIManagerException if error occurred while generating access token - * @throws UserStoreException if error ocurred while getting admin username. + * @throws UserStoreException if error occurred while getting admin username. */ private ApiApplicationKey getClientCredentials(String tenantDomain, String[] tags, String applicationName, - String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { + String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { APIRegistrationProfile registrationProfile = new APIRegistrationProfile(); registrationProfile.setAllowedToAllDomains(false); @@ -351,7 +379,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe registrationProfile.setTags(tags); registrationProfile.setApplicationName(applicationName); - ApiApplicationKey info = null; if (tenantDomain == null || tenantDomain.isEmpty()) { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } @@ -362,14 +389,49 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() .getAdminUserName()); - if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) { - info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), - registrationProfile.getTags(), tokenType, null, - registrationProfile.isAllowedToAllDomains(), validityPeriod); - } + return generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), + registrationProfile.getTags(), tokenType, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(), + registrationProfile.isAllowedToAllDomains(), validityPeriod, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); } finally { PrivilegedCarbonContext.endTenantFlow(); } - return info; + } + + private ApiApplicationInfo getApplicationInfo(String username, String password) + throws APIManagerException { + + APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance() + .getApiApplicationServices(); + + APIApplicationKey apiApplicationKey; + io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo accessTokenInfo; + try { + if (username == null || password == null) { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForConsumerRestCalls", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + } else { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentialsWithUser( + "ClientForConsumerRestCalls", + username, password, + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); + } + accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + } catch (APIServicesException e) { + String errorMsg = "Error occurred while generating the API application"; + log.error(errorMsg, e); + throw new APIManagerException(errorMsg, e); + } + + ApiApplicationInfo applicationInfo = new ApiApplicationInfo(); + applicationInfo.setClientId(apiApplicationKey.getClientId()); + applicationInfo.setClientSecret(apiApplicationKey.getClientSecret()); + applicationInfo.setAccess_token(accessTokenInfo.getAccess_token()); + applicationInfo.setRefresh_token(accessTokenInfo.getRefresh_token()); + + return applicationInfo; } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java index 27b8b2a189..e3bbebc4d0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java @@ -18,8 +18,11 @@ package io.entgra.device.mgt.core.apimgt.application.extension.internal; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; -import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; +import io.entgra.device.mgt.core.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.user.core.service.RealmService; @@ -35,6 +38,9 @@ public class APIApplicationManagerExtensionDataHolder { private TenantRegistryLoader tenantRegistryLoader; private TenantIndexingLoader indexLoader; private JWTClientManagerService jwtClientManagerService; + private ConsumerRESTAPIServices consumerRESTAPIServices; + private APIApplicationServices apiApplicationServices; + private MetadataManagementService metadataManagementService; private APIApplicationManagerExtensionDataHolder() { } @@ -104,4 +110,28 @@ public class APIApplicationManagerExtensionDataHolder { public void setJwtClientManagerService(JWTClientManagerService jwtClientManagerService) { this.jwtClientManagerService = jwtClientManagerService; } + + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } + + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } + + public MetadataManagementService getMetadataManagementService() { + return metadataManagementService; + } + + public void setMetadataManagementService(MetadataManagementService metadataManagementService) { + this.metadataManagementService = metadataManagementService; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java index 0f0e0dc79e..b3dc6dbd9d 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java @@ -17,8 +17,11 @@ */ package io.entgra.device.mgt.core.apimgt.application.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl; +import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -115,4 +118,95 @@ public class APIApplicationManagerExtensionServiceComponent { } APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null); } + + /** + * Sets APIM Consumer REST API service. + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + @Reference( + name = "APIM.consumer.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConsumerRESTAPIServices") + protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Setting APIM Consumer REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + } + + /** + * Unset APIM Consumer REST API service + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting APIM Consumer REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setConsumerRESTAPIServices(null); + } + + + /** + * Sets DCR REST API service. + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + @Reference( + name = "APIM.application.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIApplicationServices") + protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Setting DCR REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + } + + /** + * Unset DCR REST API service + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting DCR REST API Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setApiApplicationServices(null); + } + + /** + * Sets Meta Data Mgt service. + * + * @param metadataManagementService An instance of MetadataManagementService + */ + @Reference( + name = "meta.data.mgt.service", + service = io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAMetaMgtServices") + protected void setMetaMgtServices(MetadataManagementService metadataManagementService) { + if (log.isDebugEnabled()) { + log.debug("Setting Meta data mgt Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(metadataManagementService); + } + + /** + * Unset Meta Data Mgt service + * + * @param metadataManagementService An instance of MetadataManagementService + */ + protected void unsetAMetaMgtServices(MetadataManagementService metadataManagementService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Meta Data mgt Service"); + } + APIApplicationManagerExtensionDataHolder.getInstance().setMetadataManagementService(null); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index 0529a0a238..b7dc08b380 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java index d628c4ce25..7b14f48800 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java @@ -24,7 +24,11 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIService public interface APIApplicationServices { - APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; + APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) + throws APIServicesException; + + APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType) + throws APIServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java index 2f6d5d5fa4..68ea575e02 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java @@ -44,7 +44,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices { getAPIManagerConfigurationService().getAPIManagerConfiguration(); @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() + public APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) throws APIServicesException { String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); @@ -53,8 +53,8 @@ public class APIApplicationServicesImpl implements APIApplicationServices { JSONObject jsonObject = new JSONObject(); jsonObject.put("callbackUrl", Constants.EMPTY_STRING); - jsonObject.put("clientName", Constants.CLIENT_NAME); - jsonObject.put("grantType", Constants.GRANT_TYPE); + jsonObject.put("clientName", clientName); + jsonObject.put("grantType", grantType); jsonObject.put("owner", serverUser); jsonObject.put("saasApp", true); @@ -74,6 +74,35 @@ public class APIApplicationServicesImpl implements APIApplicationServices { } } + @Override + public APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType) + throws APIServicesException { + + String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("callbackUrl", Constants.EMPTY_STRING); + jsonObject.put("clientName", clientName); + jsonObject.put("grantType", grantType); + jsonObject.put("owner", username); + jsonObject.put("saasApp", true); + + RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); + Request request = new Request.Builder() + .url(applicationEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(username, password)) + .post(requestBody) + .build(); + try { + Response response = client.newCall(request).execute(); + return gson.fromJson(response.body().string(), APIApplicationKey.class); + } catch (IOException e) { + msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(e); + } + } + @Override public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) throws APIServicesException { diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java new file mode 100644 index 0000000000..2cb3cf692c --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServices.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api; + +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; + +import java.util.List; +import java.util.Map; + +public interface ConsumerRESTAPIServices { + + Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map queryParams, Map headerParams) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager, + String validityTime, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager, + List supportedGrantTypes, String callbackUrl) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException; +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java new file mode 100644 index 0000000000..998331cc0d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/ConsumerRESTAPIServicesImpl.java @@ -0,0 +1,674 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; +import okhttp3.*; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices { + + private static final Log log = LogFactory.getLog(ConsumerRESTAPIServicesImpl.class); + private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final Gson gson = new Gson(); + private static final String host = System.getProperty(Constants.IOT_CORE_HOST); + private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port; + + @Override + public Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApplicationsUrl = endPointPrefix + Constants.APPLICATIONS_API + "?query=" + appName; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllApplicationsUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray applicationList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(applicationList.toString(), Application[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllApplications(refreshedApiApplicationInfo, appName); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDetailsOfAPPUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; + + Request.Builder builder = new Request.Builder(); + builder.url(getDetailsOfAPPUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), Application.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getDetailsOfAnApplication(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API; + + JSONArray groups = new JSONArray(); + JSONArray subscriptionScope = new JSONArray(); + + if (application.getGroups() != null && application.getSubscriptionScopes() != null) { + for (String string : application.getGroups()) { + groups.put(string); + } + for (Scopes string : application.getSubscriptionScopes()) { + subscriptionScope.put(string); + } + } + + JSONObject applicationInfo = new JSONObject(); + applicationInfo.put("name", application.getName()); + applicationInfo.put("throttlingPolicy", application.getThrottlingPolicy()); + applicationInfo.put("description", application.getDescription()); + applicationInfo.put("tokenType", application.getTokenType()); + applicationInfo.put("groups", groups); + applicationInfo.put("attributes", new JSONObject()); + applicationInfo.put("subscriptionScopes", subscriptionScope); + + RequestBody requestBody = RequestBody.create(JSON, applicationInfo.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return gson.fromJson(response.body().string(), Application.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createApplication(refreshedApiApplicationInfo, application); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String deleteScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; + + Request.Builder builder = new Request.Builder(); + builder.url(deleteScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.delete(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return deleteApplication(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "?applicationId=" + applicationId + "&limit=1000"; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray subscriptionList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(subscriptionList.toString(), Subscription[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllSubscriptions(refreshedApiApplicationInfo, applicationId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map queryParams, Map headerParams) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API); + + for (Map.Entry query : queryParams.entrySet()) { + getAPIsURL.append(Constants.AMPERSAND).append(query.getKey()).append(Constants.EQUAL).append(query.getValue()); + } + + Request.Builder builder = new Request.Builder(); + builder.url(getAPIsURL.toString()); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + for (Map.Entry header : headerParams.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(apiList.toString(), APIInfo[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllApis(refreshedApiApplicationInfo, queryParams, headerParams); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String createSubscriptionUrl = endPointPrefix + Constants.SUBSCRIPTION_API; + + JSONObject subscriptionObject = new JSONObject(); + subscriptionObject.put("applicationId", subscriptions.getApplicationId()); + subscriptionObject.put("apiId", subscriptions.getApiId()); + subscriptionObject.put("throttlingPolicy", subscriptions.getThrottlingPolicy()); + subscriptionObject.put("requestedThrottlingPolicy", subscriptions.getRequestedThrottlingPolicy()); + + RequestBody requestBody = RequestBody.create(JSON, subscriptionObject.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(createSubscriptionUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return gson.fromJson(response.body().string(), Subscription.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createSubscription(refreshedApiApplicationInfo, subscriptions); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List subscriptions) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String createSubscriptionsUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "/multiple"; + + String subscriptionsList = gson.toJson(subscriptions); + RequestBody requestBody = RequestBody.create(JSON, subscriptionsList); + + Request.Builder builder = new Request.Builder(); + builder.url(createSubscriptionsUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), Subscription[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return createSubscriptions(refreshedApiApplicationInfo, subscriptions); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager, + String validityTime, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String generateApplicationKeysUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + + applicationId + "/generate-keys"; + + JSONArray grantTypesToBeSupported = new JSONArray(); + grantTypesToBeSupported.put("password"); + grantTypesToBeSupported.put("client_credentials"); + + JSONArray scopes = new JSONArray(); + scopes.put("am_application_scope"); + scopes.put("default"); + + JSONObject keyInfo = new JSONObject(); + keyInfo.put("keyType", keyType); + keyInfo.put("keyManager", keyManager); + keyInfo.put("grantTypesToBeSupported", grantTypesToBeSupported); + keyInfo.put("callbackUrl", ""); + keyInfo.put("scopes", scopes); + keyInfo.put("validityTime", 3600); + keyInfo.put("additionalProperties", new JSONObject()); + + RequestBody requestBody = RequestBody.create(JSON, keyInfo.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(generateApplicationKeysUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return generateApplicationKeys(refreshedApiApplicationInfo, applicationId, keyManager, validityTime, keyType); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + + application.getApplicationId() + "/map-keys"; + + JSONObject payload = new JSONObject(); + payload.put("consumerKey", apiApplicationInfo.getClientId()); + payload.put("consumerSecret", apiApplicationInfo.getClientSecret()); + payload.put("keyManager", keyManager); + payload.put("keyType", keyType); + + RequestBody requestBody = RequestBody.create(JSON, payload.toString()); + + Request.Builder builder = new Request.Builder(); + builder.url(getAllScopesUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.post(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return mapApplicationKeys(refreshedApiApplicationInfo, application, keyManager, keyType); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; + + Request.Builder builder = new Request.Builder(); + builder.url(getKeyDetails); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getKeyDetails(refreshedApiApplicationInfo, applicationId, keyMapId); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager, + List supportedGrantTypes, String callbackUrl) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; + + Request.Builder builder = new Request.Builder(); + builder.url(getKeyDetails); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + + JSONArray supportedGrantTypeList = new JSONArray(); + for (String string : supportedGrantTypes) { + supportedGrantTypeList.put(string); + } + + JSONObject payload = new JSONObject(); + payload.put("keyMappingId", keyMapId); + payload.put("keyManager", keyManager); + payload.put("supportedGrantTypes", supportedGrantTypeList); + payload.put("callbackUrl", (callbackUrl != null ? callbackUrl : "")); + payload.put("additionalProperties", new JSONObject()); + + RequestBody requestBody = RequestBody.create(JSON, payload.toString()); + + builder.put(requestBody); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), ApplicationKey.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return updateGrantType(refreshedApiApplicationInfo, applicationId, keyMapId, keyManager, supportedGrantTypes, callbackUrl); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllKeyManagersUrl = endPointPrefix + Constants.KEY_MANAGERS_API; + + Request.Builder builder = new Request.Builder(); + builder.url(getAllKeyManagersUrl); + builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + apiApplicationInfo.getAccess_token()); + builder.get(); + Request request = builder.build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONArray keyManagerList = (JSONArray) new JSONObject(response.body().string()).get("list"); + return gson.fromJson(keyManagerList.toString(), KeyManager[].class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), + apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); + ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); + return getAllKeyManagers(refreshedApiApplicationInfo); + //TODO: max attempt count + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + private ApiApplicationInfo returnApplicationInfo(ApiApplicationInfo apiApplicationInfo, AccessTokenInfo refreshedToken) { + + ApiApplicationInfo applicationInfo = new ApiApplicationInfo(); + applicationInfo.setClientId(apiApplicationInfo.getClientId()); + applicationInfo.setClientSecret(apiApplicationInfo.getClientSecret()); + applicationInfo.setAccess_token(refreshedToken.getAccess_token()); + applicationInfo.setRefresh_token(refreshedToken.getRefresh_token()); + return applicationInfo; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java new file mode 100644 index 0000000000..0435fc64ec --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIInfo.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * This class represents the Consumer API Information. + */ + +public class APIInfo { + + private String id; + private String name; + private String description; + private String context; + private String version; + private String provider; + private String lifeCycleStatus; + private String thumbnailUri; + private String avgRating; + private List throttlingPolicies; + private JSONObject advertiseInfo; + private JSONObject businessInformation; + private boolean isSubscriptionAvailable; + private String monetizationLabel; + private String gatewayVendor; + private List additionalProperties; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getLifeCycleStatus() { + return lifeCycleStatus; + } + + public void setLifeCycleStatus(String lifeCycleStatus) { + this.lifeCycleStatus = lifeCycleStatus; + } + + public String getThumbnailUri() { + return thumbnailUri; + } + + public void setThumbnailUri(String thumbnailUri) { + this.thumbnailUri = thumbnailUri; + } + + public String getAvgRating() { + return avgRating; + } + + public void setAvgRating(String avgRating) { + this.avgRating = avgRating; + } + + public List getThrottlingPolicies() { + return throttlingPolicies; + } + + public void setThrottlingPolicies(List throttlingPolicies) { + this.throttlingPolicies = throttlingPolicies; + } + + public JSONObject getAdvertiseInfo() { + return advertiseInfo; + } + + public void setAdvertiseInfo(JSONObject advertiseInfo) { + this.advertiseInfo = advertiseInfo; + } + + public JSONObject getBusinessInformation() { + return businessInformation; + } + + public void setBusinessInformation(JSONObject businessInformation) { + this.businessInformation = businessInformation; + } + + public boolean isSubscriptionAvailable() { + return isSubscriptionAvailable; + } + + public void setSubscriptionAvailable(boolean subscriptionAvailable) { + isSubscriptionAvailable = subscriptionAvailable; + } + + public String getMonetizationLabel() { + return monetizationLabel; + } + + public void setMonetizationLabel(String monetizationLabel) { + this.monetizationLabel = monetizationLabel; + } + + public String getGatewayVendor() { + return gatewayVendor; + } + + public void setGatewayVendor(String gatewayVendor) { + this.gatewayVendor = gatewayVendor; + } + + public List getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(List additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java new file mode 100644 index 0000000000..5cdaa83577 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/APIKey.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +/** + * This class represents the Consumer API Key Information. + */ + +public class APIKey { + + private String apikey; + private int validityTime; + + public String getApikey() { + return apikey; + } + + public void setApikey(String apikey) { + this.apikey = apikey; + } + + public int getValidityTime() { + return validityTime; + } + + public void setValidityTime(int validityTime) { + this.validityTime = validityTime; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java new file mode 100644 index 0000000000..d56de0331d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Application.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.wso2.carbon.apimgt.api.model.APIKey; + +import java.util.List; +import java.util.Map; + +/** + * This class represents the Consumer Application Information. + */ + +public class Application { + private String applicationId; + private String name; + private String throttlingPolicy; + private String description; + private String tokenType; + private String status; + private List groups; + private int subscriptionCount; + private List keys; + private Map attributes; + private List subscriptionScopes; + private String owner; + private boolean hashEnabled; + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getThrottlingPolicy() { + return throttlingPolicy; + } + + public void setThrottlingPolicy(String throttlingPolicy) { + this.throttlingPolicy = throttlingPolicy; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public int getSubscriptionCount() { + return subscriptionCount; + } + + public void setSubscriptionCount(int subscriptionCount) { + this.subscriptionCount = subscriptionCount; + } + + public List getKeys() { + return keys; + } + + public void setKeys(List keys) { + this.keys = keys; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public List getSubscriptionScopes() { + return subscriptionScopes; + } + + public void setSubscriptionScopes(List subscriptionScopes) { + this.subscriptionScopes = subscriptionScopes; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public boolean isHashEnabled() { + return hashEnabled; + } + + public void setHashEnabled(boolean hashEnabled) { + this.hashEnabled = hashEnabled; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java new file mode 100644 index 0000000000..9634b77528 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationConfigurations.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import io.apicurio.datamodels.asyncapi.v2.visitors.Aai20Traverser; + +import java.util.List; + +/** + * This class represents the Consumer Application configuration Information. + */ +public class ApplicationConfigurations { + + private String name; + private String label; + private String type; + private boolean required; + private boolean mask; + private boolean multiple; + private String tooltip; + private List values; + private String defaults; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public boolean isMask() { + return mask; + } + + public void setMask(boolean mask) { + this.mask = mask; + } + + public boolean isMultiple() { + return multiple; + } + + public void setMultiple(boolean multiple) { + this.multiple = multiple; + } + + public String getTooltip() { + return tooltip; + } + + public void setTooltip(String tooltip) { + this.tooltip = tooltip; + } + + public List getValues() { + return values; + } + + public void setValues(List values) { + this.values = values; + } + + public String getDefaults() { + return defaults; + } + + public void setDefaults(String defaults) { + this.defaults = defaults; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java new file mode 100644 index 0000000000..b7d5e2e8b9 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationGrantTypeUpdater.java @@ -0,0 +1,26 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import java.util.ArrayList; + +public class ApplicationGrantTypeUpdater { + + private String callbackUrl; + + private ArrayList supportedGrantTypes; + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java new file mode 100644 index 0000000000..c51564af2c --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/ApplicationKey.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +import java.util.List; + +/** + * This class represents the Consumer Application key Information. + */ +public class ApplicationKey { + + private String keyMappingId; + private String keyManager; + private String consumerKey; + private String consumerSecret; + private List supportedGrantTypes; + private String callbackUrl; + private String keyState; + private String keyType; + private String mode; + private String groupId; + private JSONObject token; + private JSONObject additionalProperties; + + public String getKeyMappingId() { + return keyMappingId; + } + + public void setKeyMappingId(String keyMappingId) { + this.keyMappingId = keyMappingId; + } + + public String getKeyManager() { + return keyManager; + } + + public void setKeyManager(String keyManager) { + this.keyManager = keyManager; + } + + public String getConsumerKey() { + return consumerKey; + } + + public void setConsumerKey(String consumerKey) { + this.consumerKey = consumerKey; + } + + public String getConsumerSecret() { + return consumerSecret; + } + + public void setConsumerSecret(String consumerSecret) { + this.consumerSecret = consumerSecret; + } + + public List getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(List supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public String getKeyState() { + return keyState; + } + + public void setKeyState(String keyState) { + this.keyState = keyState; + } + + public String getKeyType() { + return keyType; + } + + public void setKeyType(String keyType) { + this.keyType = keyType; + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public JSONObject getToken() { + return token; + } + + public void setToken(JSONObject token) { + this.token = token; + } + + public JSONObject getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(JSONObject additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java new file mode 100644 index 0000000000..ac34e006dd --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/KeyManager.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +import java.util.List; + +/** + * This class represents the Consumer Key manager Information. + */ + +public class KeyManager { + + private String id; + private String name; + private String type; + private String displayName; + private String description; + private boolean enabled; + private List availableGrantTypes; + private String tokenEndpoint; + private String revokeEndpoint; + private String userInfoEndpoint; + private String enableTokenGeneration; + private String enableTokenEncryption; + private String enableTokenHashing; + private String enableOAuthAppCreation; + private String enableMapOAuthConsumerApps; + private List applicationConfiguration; + private JSONObject additionalProperties; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public List getAvailableGrantTypes() { + return availableGrantTypes; + } + + public void setAvailableGrantTypes(List availableGrantTypes) { + this.availableGrantTypes = availableGrantTypes; + } + + public String getTokenEndpoint() { + return tokenEndpoint; + } + + public void setTokenEndpoint(String tokenEndpoint) { + this.tokenEndpoint = tokenEndpoint; + } + + public String getRevokeEndpoint() { + return revokeEndpoint; + } + + public void setRevokeEndpoint(String revokeEndpoint) { + this.revokeEndpoint = revokeEndpoint; + } + + public String getUserInfoEndpoint() { + return userInfoEndpoint; + } + + public void setUserInfoEndpoint(String userInfoEndpoint) { + this.userInfoEndpoint = userInfoEndpoint; + } + + public String getEnableTokenGeneration() { + return enableTokenGeneration; + } + + public void setEnableTokenGeneration(String enableTokenGeneration) { + this.enableTokenGeneration = enableTokenGeneration; + } + + public String getEnableTokenEncryption() { + return enableTokenEncryption; + } + + public void setEnableTokenEncryption(String enableTokenEncryption) { + this.enableTokenEncryption = enableTokenEncryption; + } + + public String getEnableTokenHashing() { + return enableTokenHashing; + } + + public void setEnableTokenHashing(String enableTokenHashing) { + this.enableTokenHashing = enableTokenHashing; + } + + public String getEnableOAuthAppCreation() { + return enableOAuthAppCreation; + } + + public void setEnableOAuthAppCreation(String enableOAuthAppCreation) { + this.enableOAuthAppCreation = enableOAuthAppCreation; + } + + public String getEnableMapOAuthConsumerApps() { + return enableMapOAuthConsumerApps; + } + + public void setEnableMapOAuthConsumerApps(String enableMapOAuthConsumerApps) { + this.enableMapOAuthConsumerApps = enableMapOAuthConsumerApps; + } + + public List getApplicationConfiguration() { + return applicationConfiguration; + } + + public void setApplicationConfiguration(List applicationConfiguration) { + this.applicationConfiguration = applicationConfiguration; + } + + public JSONObject getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(JSONObject additionalProperties) { + this.additionalProperties = additionalProperties; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java new file mode 100644 index 0000000000..a2b55005b6 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Scopes.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import java.util.List; + +/** + * This class represents the scope data. + */ + +public class Scopes { + + private String key; + private String name; + private List roles; + private String description; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java new file mode 100644 index 0000000000..2ff525f5dc --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/APIMConsumer/Subscription.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer; + +import org.json.JSONObject; + +public class Subscription { + + private String subscriptionId; + private String applicationId; + private String apiId; + private APIInfo apiInfo; + private JSONObject applicationInfo; + private String throttlingPolicy; + private String requestedThrottlingPolicy; + private String status; + private String redirectionParams; + + public String getSubscriptionId() { + return subscriptionId; + } + + public void setSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String getApiId() { + return apiId; + } + + public void setApiId(String apiId) { + this.apiId = apiId; + } + + public APIInfo getApiInfo() { + return apiInfo; + } + + public void setApiInfo(APIInfo apiInfo) { + this.apiInfo = apiInfo; + } + + public JSONObject getApplicationInfo() { + return applicationInfo; + } + + public void setApplicationInfo(JSONObject applicationInfo) { + this.applicationInfo = applicationInfo; + } + + public String getThrottlingPolicy() { + return throttlingPolicy; + } + + public void setThrottlingPolicy(String throttlingPolicy) { + this.throttlingPolicy = throttlingPolicy; + } + + public String getRequestedThrottlingPolicy() { + return requestedThrottlingPolicy; + } + + public void setRequestedThrottlingPolicy(String requestedThrottlingPolicy) { + this.requestedThrottlingPolicy = requestedThrottlingPolicy; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getRedirectionParams() { + return redirectionParams; + } + + public void setRedirectionParams(String redirectionParams) { + this.redirectionParams = redirectionParams; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java index 14d5056b45..6ca26f74f0 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java @@ -24,17 +24,20 @@ public final class Constants { } public static final String EMPTY_STRING = ""; - public static final String CLIENT_NAME = "rest_api_publisher_code"; + public static final String AMPERSAND = "&"; + public static final String SLASH = "/"; + public static final String EQUAL = "="; public static final String SERVER_USER = "WorkflowConfigurations.ServerUser"; public static final String SERVER_PASSWORD = "WorkflowConfigurations.ServerPassword"; - public static final String GRANT_TYPE = "client_credentials password refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME = "refresh_token"; public static final String OAUTH_EXPIRES_IN = "expires_in"; public static final String OAUTH_TOKEN_SCOPE = "scope"; public static final String OAUTH_TOKEN_TYPE = "token_type"; public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String SCOPE_PARAM_NAME = "scope"; - public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export apim:api_publish"; + public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export " + + "apim:api_publish apim:admin apim:api_key apim:app_import_export apim:app_manage apim:store_settings " + + "apim:sub_alert_manage apim:sub_manage apim:subscribe openid"; public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; @@ -65,6 +68,10 @@ public final class Constants { public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v4/scopes/"; public static final String API_ENDPOINT = "/api/am/publisher/v4/apis/"; public static final String GET_ALL_APIS = "/api/am/publisher/v4/apis?limit=1000"; + public static final String APPLICATIONS_API = "/api/am/devportal/v3/applications"; + public static final String SUBSCRIPTION_API = "/api/am/devportal/v3/subscriptions"; + public static final String DEV_PORTAL_API = "/api/am/devportal/v3/apis?limit=1000"; + public static final String KEY_MANAGERS_API = "/api/am/devportal/v3/key-managers"; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java new file mode 100644 index 0000000000..169ce76442 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/ApiApplicationInfo.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.apimgt.extension.rest.api.dto; + +/** + * This holds the API application client information and token information. + */ +public class ApiApplicationInfo { + private String clientId; + private String clientSecret; + private String refresh_token; + private String access_token; + + 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 getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java index 9a53757b0b..4995df95ef 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIDataHolder.java @@ -19,6 +19,7 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; public class PublisherRESTAPIDataHolder { @@ -26,6 +27,8 @@ public class PublisherRESTAPIDataHolder { private APIApplicationServices apiApplicationServices; private APIManagerConfigurationService apiManagerConfigurationService; + private ConsumerRESTAPIServices consumerRESTAPIServices; + private static PublisherRESTAPIDataHolder thisInstance = new PublisherRESTAPIDataHolder(); private PublisherRESTAPIDataHolder() { @@ -54,4 +57,12 @@ public class PublisherRESTAPIDataHolder { return apiManagerConfigurationService; } + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } + } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java index 62b378923b..f5d000fc7f 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/PublisherRESTAPIServiceComponent.java @@ -20,6 +20,8 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServicesImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -32,7 +34,7 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; immediate = true) public class PublisherRESTAPIServiceComponent { - private static Log log = LogFactory.getLog(PublisherRESTAPIServiceComponent.class); + private static final Log log = LogFactory.getLog(PublisherRESTAPIServiceComponent.class); @Activate protected void activate(ComponentContext componentContext) { @@ -46,6 +48,10 @@ public class PublisherRESTAPIServiceComponent { bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); PublisherRESTAPIDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + ConsumerRESTAPIServices consumerRESTAPIServices = new ConsumerRESTAPIServicesImpl(); + bundleContext.registerService(ConsumerRESTAPIServices.class.getName(), consumerRESTAPIServices, null); + PublisherRESTAPIDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + if (log.isDebugEnabled()) { log.debug("API Application bundle has been successfully initialized"); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml index 02f206b74a..4d34bce5f8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT 4.0.0 diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java index c8171451f6..9235087a77 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/DCRRequest.java @@ -22,6 +22,7 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; @XmlRootElement @@ -32,6 +33,8 @@ public class DCRRequest { @XmlElement(required = true) private String username; @XmlElement(required = true) + private String password; + @XmlElement(required = true) private String grantTypes; @XmlElement private String callBackUrl; @@ -43,6 +46,10 @@ public class DCRRequest { @XmlElement private int validityPeriod; + private String callbackUrl; + + private ArrayList supportedGrantTypes; + public String getApplicationName() { return applicationName; } @@ -98,4 +105,24 @@ public class DCRRequest { public void setValidityPeriod(int validityPeriod) { this.validityPeriod = validityPeriod; } + + public String getPassword() { return password; } + + public void setPassword(String password) { this.password = password; } + + public String getCallbackUrl() { + return callbackUrl; + } + + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + public ArrayList getSupportedGrantTypes() { + return supportedGrantTypes; + } + + public void setSupportedGrantTypes(ArrayList supportedGrantTypes) { + this.supportedGrantTypes = supportedGrantTypes; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java index 96f506d99e..54cb0e98e1 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.api/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtExcepti import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException; +import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -45,8 +46,11 @@ public class KeyManagerServiceImpl implements KeyManagerService { public Response dynamicClientRegistration(DCRRequest dcrRequest) { try { KeyMgtService keyMgtService = new KeyMgtServiceImpl(); + //todo lasantha - can pass password from here - modify DCRRequest object DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), - dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod()); + dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), + dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod(), dcrRequest.getPassword(), + dcrRequest.getSupportedGrantTypes(), dcrRequest.getCallbackUrl()); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); } catch (KeyMgtException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml index 8b1385eced..6b2581ae08 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/pom.xml @@ -21,7 +21,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml @@ -55,6 +55,11 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.common + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.apimgt.extension.rest.api + + @@ -108,6 +113,7 @@ org.wso2.carbon.apimgt.keymgt.model;version="[9.28,10)", org.wso2.carbon.apimgt.keymgt.model.entity;version="[9.28,10)", org.wso2.carbon.apimgt.keymgt.service;version="[9.28,10)", + io.entgra.device.mgt.core.apimgt.extension.rest.api, org.wso2.carbon.context;version="[4.8,5)", org.wso2.carbon.user.api;version="[1.0,2)", org.wso2.carbon.user.core.service;version="[4.8,5)", diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java index 5aa4d6e6aa..0faf78683c 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/exception/KeyMgtException.java @@ -28,5 +28,9 @@ public class KeyMgtException extends Exception { public KeyMgtException(String errorMessage) { super(errorMessage); } + + public KeyMgtException(String errorMessage, Exception e) { + super(errorMessage, e); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java index fd711781a1..96e96000be 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtDataHolder.java @@ -18,12 +18,16 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; public class KeyMgtDataHolder { private static final KeyMgtDataHolder thisInstance = new KeyMgtDataHolder(); private KeyMgtService keyMgtService; + private ConsumerRESTAPIServices consumerRESTAPIServices; + private APIApplicationServices apiApplicationServices; public static KeyMgtDataHolder getInstance() { return thisInstance; @@ -37,4 +41,20 @@ public class KeyMgtDataHolder { this.keyMgtService = keyMgtService; } + + public ConsumerRESTAPIServices getConsumerRESTAPIServices() { + return consumerRESTAPIServices; + } + + public void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + this.consumerRESTAPIServices = consumerRESTAPIServices; + } + + public APIApplicationServices getApiApplicationServices() { + return apiApplicationServices; + } + + public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { + this.apiApplicationServices = apiApplicationServices; + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java index 395bdc0107..96a05f15f5 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/internal/KeyMgtServiceComponent.java @@ -18,15 +18,16 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.internal; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; 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.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.*; + @Component( name = "io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtServiceComponent", immediate = true) @@ -63,4 +64,64 @@ public class KeyMgtServiceComponent { log.debug("De-activating Key Management Service Component"); } } + + /** + * Sets APIM Consumer REST API service. + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + @Reference( + name = "APIM.consumer.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetConsumerRESTAPIServices") + protected void setConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Setting APIM Consumer REST API Service"); + } + KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(consumerRESTAPIServices); + } + + /** + * Unset APIM Consumer REST API service + * + * @param consumerRESTAPIServices An instance of ConsumerRESTAPIServices + */ + protected void unsetConsumerRESTAPIServices(ConsumerRESTAPIServices consumerRESTAPIServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting APIM Consumer REST API Service"); + } + KeyMgtDataHolder.getInstance().setConsumerRESTAPIServices(null); + } + + /** + * Sets DCR REST API service. + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + @Reference( + name = "APIM.application.service", + service = io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices.class, + cardinality = ReferenceCardinality.MANDATORY, + policy = ReferencePolicy.DYNAMIC, + unbind = "unsetAPIApplicationServices") + protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Setting DCR REST API Service"); + } + KeyMgtDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); + } + + /** + * Unset DCR REST API service + * + * @param apiApplicationServices An instance of APIApplicationServices + */ + protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { + if (log.isDebugEnabled()) { + log.debug("Unsetting DCR REST API Service"); + } + KeyMgtDataHolder.getInstance().setApiApplicationServices(null); + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java index f08f92d8c7..b1ecb3c77b 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtService.java @@ -24,6 +24,8 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import java.util.List; + public interface KeyMgtService { /*** @@ -35,11 +37,13 @@ public interface KeyMgtService { * @param callBackUrl callback url of the application * @param tags api tags for api subscription of the application * @param isSaasApp if the application is a saas app + * @param password Password of the owner * @return @{@link DCRResponse} DCR Response object with client credentials * @throws KeyMgtException if any error occurs during DCR process */ DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException; + String[] tags, boolean isSaasApp, int validityPeriod, String password, + List supportedGrantTypes, String callbackUrl) throws KeyMgtException; /*** * This method will handle the access token requests diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java index f0b48aab6a..5afd9dbc65 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension/src/main/java/io/entgra/device/mgt/core/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java @@ -19,9 +19,14 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.service; import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.*; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtDataHolder; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations; @@ -29,10 +34,8 @@ import okhttp3.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.Application; -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.user.api.UserRealm; @@ -62,7 +65,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, - String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException { + String[] tags, boolean isSaasApp, int validityPeriod, + String password, List supportedGrantTypes, String callbackUrl) throws KeyMgtException { if (owner == null) { PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -83,20 +87,22 @@ public class KeyMgtServiceImpl implements KeyMgtService { .getTenantManager().getTenantId(tenantDomain); } catch (UserStoreException e) { msg = "Error while loading tenant configuration"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } kmConfig = getKeyManagerConfig(); if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { - OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod); + OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, + validityPeriod, kmConfig.getAdminPassword(), supportedGrantTypes, callbackUrl); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); } else { // super-tenant admin dcr and token generation + //todo lasantha null passed in last two params OAuthApplication superTenantOauthApp = createOauthApplication( KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, - kmConfig.getAdminUsername(), null, validityPeriod); + kmConfig.getAdminUsername(), null, validityPeriod, kmConfig.getAdminPassword(), null, null); String superAdminAccessToken = createAccessToken(superTenantOauthApp); // create new key manager for the tenant, under super-tenant space @@ -112,18 +118,25 @@ public class KeyMgtServiceImpl implements KeyMgtService { .getRealmProperty("reserved_tenant_user_password"); } catch (UserStoreException e) { msg = "Error while loading user realm configuration"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } createUserIfNotExists(subTenantUserUsername, subTenantUserPassword); // DCR for the requesting user - OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod); + //todo lasantha -> need to pass password of user + //todo lasantha null passed in last two params + + OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod, + password, null, null); String requestingUserAccessToken = createAccessToken(dcrApplication); // get application id - Application application = getApplication(clientName, owner); - String applicationUUID = application.getUUID(); + //todo --> can use requestingUserAccessToken token here to get application data - modify getApplication + // method signature + + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = getApplication(clientName, owner); + String applicationUUID = application.getApplicationId(); // do app key mapping mapApplicationKeys(dcrApplication.getClientId(), dcrApplication.getClientSecret(), keyManagerName, @@ -308,13 +321,18 @@ public class KeyMgtServiceImpl implements KeyMgtService { * @return @{@link OAuthApplication} OAuth application object * @throws KeyMgtException if any error occurs while creating response object */ - private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException { - String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod); + private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, + int validityPeriod, String ownerPassword, + List supportedGrantTypes, String callbackUrl) throws KeyMgtException { + //todo modify this to pass the password as well + String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod, + ownerPassword, supportedGrantTypes, callbackUrl); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); kmConfig = getKeyManagerConfig(); String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; String username, password; + //todo why can't we use owner details here? if (KeyMgtConstants.SUPER_TENANT.equals(MultitenantUtils.getTenantDomain(owner))) { username = kmConfig.getAdminUsername(); password = kmConfig.getAdminPassword(); @@ -323,6 +341,7 @@ public class KeyMgtServiceImpl implements KeyMgtService { password = subTenantUserPassword; } + //todo why can't we use owner details for authentication Request request = new Request.Builder() .url(dcrEndpoint) .addHeader(KeyMgtConstants.AUTHORIZATION_HEADER, Credentials.basic(username, password)) @@ -332,7 +351,7 @@ public class KeyMgtServiceImpl implements KeyMgtService { Response response = client.newCall(request).execute(); return gson.fromJson(response.body().string(), OAuthApplication.class); } catch (IOException e) { - msg = "Error occurred while processing the response"; + msg = "Error occurred while processing the response" + e; throw new KeyMgtException(msg); } } @@ -403,8 +422,8 @@ public class KeyMgtServiceImpl implements KeyMgtService { client.newCall(request).execute(); } catch (IOException e) { msg = "Error occurred while invoking create key manager endpoint"; - log.error(msg); - throw new KeyMgtException(msg); + log.error(msg, e); + throw new KeyMgtException(msg, e); } } @@ -412,28 +431,52 @@ public class KeyMgtServiceImpl implements KeyMgtService { * Retrieves an application by name and owner * * @param applicationName name of the application - * @param owner owner of the application + * @param accessToken Access Token * @return @{@link Application} Application object * @throws KeyMgtException if any error occurs while retrieving the application */ - private Application getApplication(String applicationName, String owner) throws KeyMgtException { + private io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application getApplication(String applicationName, String accessToken) throws KeyMgtException { + + ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo(); + apiApplicationInfo.setAccess_token(accessToken); try { - APIManagerFactory apiManagerFactory = APIManagerFactory.getInstance(); - APIConsumer apiConsumer = apiManagerFactory.getAPIConsumer(owner); - return null; // todo:apim - apiConsumer.getApplicationsByName(owner, applicationName, ""); - } catch (APIManagementException e) { + ConsumerRESTAPIServices consumerRESTAPIServices = + KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = + consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName); + if (applications.length == 1) { + return applications[0]; + } else { + String msg = + "Found invalid number of applications. No of applications found from the APIM: " + applications.length; + log.error(msg); + throw new KeyMgtException(msg); + } + } catch (io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException e) { msg = "Error while trying to retrieve the application"; - log.error(msg); + log.error(msg, e); + throw new KeyMgtException(msg); + } catch (UnexpectedResponseException e) { + msg = "Received invalid response for the API applications retrieving REST API call."; + log.error(msg, e); + throw new KeyMgtException(msg); + } catch (APIServicesException e) { + msg = "Error occurred while processing the API Response."; + log.error(msg, e); throw new KeyMgtException(msg); } } - private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) { + private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod, + String password, List supportedGrantTypes, String callbackUrl) { JSONObject jsonObject = new JSONObject(); jsonObject.put("applicationName", clientName); jsonObject.put("username", owner); jsonObject.put("tags", tags); jsonObject.put("validityPeriod", validityPeriod); + jsonObject.put("password", password); + jsonObject.put("supportedGrantTypes", supportedGrantTypes); + jsonObject.put("callbackUrl", callbackUrl); return jsonObject.toString(); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 15141fa9f2..4582e37e13 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -22,7 +22,7 @@ apimgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index e1a30c0d48..7bcb38002a 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -104,7 +104,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIApplicationKey apiApplicationKey; AccessTokenInfo accessTokenInfo; try { - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token" + ); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -168,19 +171,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { String apiUuid = apiIdentifier.getUUID(); if (!apiFound) { // add new scopes as shared scopes - for (ApiScope apiScope : apiConfig.getScopes()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { - Scope scope = new Scope(); - scope.setDisplayName(apiScope.getName()); - scope.setDescription(apiScope.getDescription()); - scope.setName(apiScope.getKey()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); - } - } + addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey, + accessTokenInfo); APIInfo api = getAPI(apiConfig, true); APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); apiUuid = createdAPI.getId(); @@ -220,7 +212,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { - // With 4.x to 5.x upgrade // - there cannot be same local scope assigned in 2 different APIs // - local scopes will be deprecated in the future, so need to move all scopes as shared scopes @@ -235,54 +226,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { // 1. add new scopes as shared scopes // 2. update the API adding scopes for the URI Templates - Set scopesToMoveAsSharedScopes = new HashSet<>(); - for (ApiScope apiScope : apiConfig.getScopes()) { - // if the scope is not available as shared scope, and it is assigned to an API as a local scope - // need remove the local scope and add as a shared scope - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { - //todo:apim - // if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { - if (true) { - // collect scope to move as shared scopes - scopesToMoveAsSharedScopes.add(apiScope); - } else { - // if new scope add as shared scope - Scope scope = new Scope(); - scope.setName(apiScope.getKey()); - scope.setDescription(apiScope.getDescription()); - scope.setDisplayName(apiScope.getName()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + // It is guaranteed that there is no local scope if we update from 5.0.0 to the most + // recent version. Therefore, if the scope is not already available as a shared scope, + // new scopes must be added as shared scopes. Additionally, it is necessary to + // upgrade to 5.0.0 first before updating from 5.0.0 to the most recent version if we + // are updating from a version that is older than 5.0.0. - } - } - } + addNewSharedScope(apiConfig.getScopes(), publisherRESTAPIServices, apiApplicationKey, + accessTokenInfo); // Get existing API APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); - if (scopesToMoveAsSharedScopes.size() > 0) { - // update API to remove local scopes - APIInfo api = getAPI(apiConfig, false); - api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); - - for (ApiScope apiScope : scopesToMoveAsSharedScopes) { - Scope scope = new Scope(); - scope.setName(apiScope.getKey()); - scope.setDescription(apiScope.getDescription()); - scope.setDisplayName(apiScope.getName()); - List bindings = new ArrayList<>(apiScope.getRoles()); - bindings.add(ADMIN_ROLE_KEY); - scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); - } - } - - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); APIInfo api = getAPI(apiConfig, true); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); api.setId(apiUuid); @@ -434,13 +389,43 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } + /** + * Add new Shared Scopes + * + * @param apiScopes set of API scopes + * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} + * @param apiApplicationKey API application Key + * @param accessTokenInfo Details of access token + * @throws BadRequestException if invalid payload receives to add new shared scopes. + * @throws UnexpectedResponseException if the response is not either 200 or 400. + * @throws APIServicesException if error occurred while processing the response. + */ + private void addNewSharedScope(Set apiScopes, PublisherRESTAPIServices publisherRESTAPIServices, + APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws BadRequestException, UnexpectedResponseException, APIServicesException { + for (ApiScope apiScope : apiScopes) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, + apiScope.getKey())) { + Scope scope = new Scope(); + scope.setName(apiScope.getKey()); + scope.setDescription(apiScope.getDescription()); + scope.setDisplayName(apiScope.getName()); + List bindings = new ArrayList<>(apiScope.getRoles()); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + } + } + } + public void addDefaultScopesIfNotExist() { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); try { - APIApplicationKey apiApplicationKey = - apiApplicationServices.createAndRetrieveApplicationCredentials(); + APIApplicationKey apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token" + ); AccessTokenInfo accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); @@ -479,7 +464,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIApplicationKey apiApplicationKey; AccessTokenInfo accessTokenInfo; try { - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token" + ); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -613,7 +601,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIApplicationKey apiApplicationKey; AccessTokenInfo accessTokenInfo; try { - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForPublisherRestCalls", + "client_credentials password refresh_token" + ); accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { @@ -725,16 +716,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { } private void updatePermissions(String role, List permissions) throws UserStoreException { + if (role == null || permissions == null) return; AuthorizationManager authorizationManager = APIPublisherDataHolder.getInstance().getUserRealm() .getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Updating the role '" + role + "'"); } - if (permissions != null && !permissions.isEmpty()) { - authorizationManager.clearRoleAuthorization(role); - for (String permission : permissions) { - authorizationManager.authorizeRole(role, permission, CarbonConstants.UI_PERMISSION_ACTION); - } + authorizationManager.clearRoleAuthorization(role); + for (String permission : permissions) { + authorizationManager.authorizeRole(role, permission, CarbonConstants.UI_PERMISSION_ACTION); + authorizationManager.refreshAllowedRolesForResource(permission); } } @@ -797,7 +788,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setName(apiUriTemplate.getScope().getKey()); scope.setDisplayName(apiUriTemplate.getScope().getName()); scope.setDescription(apiUriTemplate.getScope().getDescription()); - scope.setBindings(apiUriTemplate.getScope().getRoles()); + List bindings = new ArrayList<>(apiUriTemplate.getScope().getRoles()); + bindings.add(ADMIN_ROLE_KEY); + scope.setBindings(bindings); JSONObject scopeObject = new JSONObject(); scopeObject.put("scope", new JSONObject(gson.toJson(scope))); diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index e9e07fb3b9..59b57165b0 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml index 74d2f7aecf..c0e2fb95cf 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml index 5ebd2d7226..21549bb117 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core application-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml @@ -173,10 +173,9 @@ - - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 org.apache.felix diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 5dea673b5e..71dab6fb65 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -40,6 +40,7 @@ import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.TrustStrategy; import org.json.JSONArray; import org.json.JSONObject; import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; @@ -120,6 +121,8 @@ import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -186,23 +189,26 @@ public class SubscriptionManagerImpl implements SubscriptionManager { try { // Only for iOS devices int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - if (DeviceTypes.IOS.toString().equalsIgnoreCase(APIUtil.getDeviceTypeData(applicationDTO - .getDeviceTypeId()).getName())) { - // TODO: replace getAssetByAppId with the correct one in DAO - // Check if the app trying to subscribe is a VPP asset. - VppAssetDTO storedAsset = vppApplicationDAO.getAssetByAppId(applicationDTO.getId(), tenantId); - if (storedAsset != null) { // This is a VPP asset - List users = new ArrayList<>(); - List devices = applicationSubscriptionInfo.getDevices();// get - // subscribed device list, so that we can extract the users of those devices. - for (Device device : devices) { - VppUserDTO user = vppApplicationDAO.getUserByDMUsername(device.getEnrolmentInfo() - .getOwner(), PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getTenantId(true)); - users.add(user); + // Ignore checking device type if app is a web clip + if(!applicationDTO.getType().equals("WEB_CLIP")){ + if (DeviceTypes.IOS.toString().equalsIgnoreCase(APIUtil.getDeviceTypeData(applicationDTO + .getDeviceTypeId()).getName())) { + // TODO: replace getAssetByAppId with the correct one in DAO + // Check if the app trying to subscribe is a VPP asset. + VppAssetDTO storedAsset = vppApplicationDAO.getAssetByAppId(applicationDTO.getId(), tenantId); + if (storedAsset != null) { // This is a VPP asset + List users = new ArrayList<>(); + List devices = applicationSubscriptionInfo.getDevices();// get + // subscribed device list, so that we can extract the users of those devices. + for (Device device : devices) { + VppUserDTO user = vppApplicationDAO.getUserByDMUsername(device.getEnrolmentInfo() + .getOwner(), PrivilegedCarbonContext.getThreadLocalCarbonContext() + .getTenantId(true)); + users.add(user); + } + VPPApplicationManager vppManager = APIUtil.getVPPManager(); + vppManager.addAssociation(storedAsset, users); } - VPPApplicationManager vppManager = APIUtil.getVPPManager(); - vppManager.addAssociation(storedAsset, users); } } } catch (BadRequestException e) { @@ -1382,7 +1388,12 @@ public class SubscriptionManagerImpl implements SubscriptionManager { private CloseableHttpClient getHttpClient() throws ApplicationManagementException { try { SSLContextBuilder builder = new SSLContextBuilder(); - builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + builder.loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + return true; + } + }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); return HttpClients.custom().setSSLSocketFactory(sslsf).useSystemProperties().build(); } catch (NoSuchAlgorithmException e) { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java index 272a5b45b0..96e4c40fd1 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/OAuthUtils.java @@ -55,16 +55,18 @@ public class OAuthUtils { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext. - getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName()); + String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); APIManagementProviderService apiManagementProviderService = (APIManagementProviderService) ctx. getOSGiService(APIManagementProviderService.class, null); apiApplicationKeyInfo = apiManagementProviderService. generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), registrationProfile.getTags(), Constants.ApplicationInstall.DEFAULT_TOKEN_TYPE, - null, registrationProfile.isAllowedToAllDomains(), - Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD); + username, registrationProfile.isAllowedToAllDomains(), + Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminPassword(), null, null, null, false); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml index 005789d0a6..4c68896de0 100644 --- a/components/application-mgt/pom.xml +++ b/components/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml index ad742cd285..5002509b66 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml index 0b0f530259..fb8dc0520f 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api/pom.xml @@ -22,7 +22,7 @@ certificate-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml index 2e5bb73e23..3a46fa2008 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core certificate-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index a5ec99203e..9116acb94c 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -53,8 +53,8 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ try { conn = this.getConnection(); stmt = conn.prepareStatement( - "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)" - + " VALUES (?,?,?,?)"); + "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME, DEVICE_IDENTIFIER)" + + " VALUES (?,?,?,?,?)"); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext. getThreadLocalCarbonContext(); String username = threadLocalCarbonContext.getUsername(); @@ -70,6 +70,7 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ stmt.setBytes(2, bytes); stmt.setInt(3, certificate.getTenantId()); stmt.setString(4, username); + stmt.setString(5, certificate.getDeviceIdentifier()); stmt.addBatch(); } stmt.executeBatch(); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 455942b305..92891754ed 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -64,11 +64,11 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { "WHERE TENANT_ID = ?"; if (StringUtils.isNotEmpty(serialNumber)) { - sql += " AND SERIAL_NUMBER = ?"; + sql += " AND SERIAL_NUMBER LIKE ?"; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - sql += " AND DEVICE_IDENTIFIER = ?"; + sql += " AND DEVICE_IDENTIFIER LIKE ?"; } if (StringUtils.isNotEmpty(username)) { @@ -80,11 +80,11 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 2; if (StringUtils.isNotEmpty(serialNumber)) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (StringUtils.isNotEmpty(deviceIdentifier)) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (StringUtils.isNotEmpty(username)) { @@ -125,12 +125,12 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { "WHERE TENANT_ID = ? "; if (StringUtils.isNotEmpty(serialNumber)) { - query += "AND SERIAL_NUMBER = ? "; + query += "AND SERIAL_NUMBER LIKE ? "; isCertificateSerialNumberProvided = true; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - query += "AND DEVICE_IDENTIFIER = ? "; + query += "AND DEVICE_IDENTIFIER LIKE ? "; isCertificateDeviceIdentifierProvided = true; } @@ -145,10 +145,10 @@ public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (isCertificateUsernameProvided) { stmt.setString(paramIdx++, "%" + username + "%"); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java index cbb689977b..9fd87d6ed0 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -64,12 +64,12 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; if (StringUtils.isNotEmpty(serialNumber)) { - query += "AND SERIAL_NUMBER = ? "; + query += "AND SERIAL_NUMBER LIKE ? "; isCertificateSerialNumberProvided = true; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - query += "AND DEVICE_IDENTIFIER = ? "; + query += "AND DEVICE_IDENTIFIER LIKE ? "; isCertificateDeviceIdentifierProvided = true; } @@ -84,10 +84,10 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (isCertificateUsernameProvided) { stmt.setString(paramIdx++, "%" + username + "%"); @@ -137,11 +137,11 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { "WHERE TENANT_ID = ?"; if (StringUtils.isNotEmpty(serialNumber)) { - sql += " AND SERIAL_NUMBER = ?"; + sql += " AND SERIAL_NUMBER LIKE ?"; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - sql += " AND DEVICE_IDENTIFIER = ?"; + sql += " AND DEVICE_IDENTIFIER LIKE ?"; } if (StringUtils.isNotEmpty(username)) { @@ -153,11 +153,11 @@ public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 2; if (StringUtils.isNotEmpty(serialNumber)) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (StringUtils.isNotEmpty(deviceIdentifier)) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (StringUtils.isNotEmpty(username)) { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java index 92b5720102..ef06ec0000 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -64,12 +64,12 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; if (StringUtils.isNotEmpty(serialNumber)) { - query += "AND SERIAL_NUMBER = ? "; + query += "AND SERIAL_NUMBER LIKE ? "; isCertificateSerialNumberProvided = true; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - query += "AND DEVICE_IDENTIFIER = ? "; + query += "AND DEVICE_IDENTIFIER LIKE ? "; isCertificateDeviceIdentifierProvided = true; } @@ -84,10 +84,10 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (isCertificateUsernameProvided) { stmt.setString(paramIdx++, "%" + username + "%"); @@ -137,15 +137,15 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { "WHERE TENANT_ID = ?"; if (StringUtils.isNotEmpty(serialNumber)) { - sql += " AND SERIAL_NUMBER = ?"; + sql += " AND SERIAL_NUMBER LIKE ?"; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - sql += " AND DEVICE_IDENTIFIER = ?"; + sql += " AND DEVICE_IDENTIFIER LIKE ?"; } if (StringUtils.isNotEmpty(username)) { - sql += " AND USERNAME ILIKE ?"; + sql += " AND USERNAME LIKE ?"; } try (PreparedStatement stmt = conn.prepareStatement(sql)) { @@ -153,11 +153,11 @@ public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 2; if (StringUtils.isNotEmpty(serialNumber)) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (StringUtils.isNotEmpty(deviceIdentifier)) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (StringUtils.isNotEmpty(username)) { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java index 80f902614d..22874dd7b7 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -64,12 +64,12 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { "FROM DM_DEVICE_CERTIFICATE " + "WHERE TENANT_ID = ? "; if (StringUtils.isNotEmpty(serialNumber)) { - query += "AND SERIAL_NUMBER = ? "; + query += "AND SERIAL_NUMBER LIKE ? "; isCertificateSerialNumberProvided = true; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - query += "AND DEVICE_IDENTIFIER = ? "; + query += "AND DEVICE_IDENTIFIER LIKE ? "; isCertificateDeviceIdentifierProvided = true; } @@ -84,10 +84,10 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 1; stmt.setInt(paramIdx++, tenantId); if (isCertificateSerialNumberProvided) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (isCertificateDeviceIdentifierProvided) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (isCertificateUsernameProvided) { stmt.setString(paramIdx++, "%" + username + "%"); @@ -137,11 +137,11 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { "WHERE TENANT_ID = ?"; if (StringUtils.isNotEmpty(serialNumber)) { - sql += " AND SERIAL_NUMBER = ?"; + sql += " AND SERIAL_NUMBER LIKE ?"; } if (StringUtils.isNotEmpty(deviceIdentifier)) { - sql += " AND DEVICE_IDENTIFIER = ?"; + sql += " AND DEVICE_IDENTIFIER LIKE ?"; } if (StringUtils.isNotEmpty(username)) { @@ -153,11 +153,11 @@ public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { int paramIdx = 2; if (StringUtils.isNotEmpty(serialNumber)) { - stmt.setString(paramIdx++, serialNumber); + stmt.setString(paramIdx++, "%" + serialNumber + "%"); } if (StringUtils.isNotEmpty(deviceIdentifier)) { - stmt.setString(paramIdx++, deviceIdentifier); + stmt.setString(paramIdx++, "%" + deviceIdentifier + "%"); } if (StringUtils.isNotEmpty(username)) { diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java index 347dea3d4f..e8a29ebc29 100755 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/main/java/io/entgra/device/mgt/core/certificate/mgt/core/impl/CertificateGenerator.java @@ -849,6 +849,7 @@ public class CertificateGenerator { new io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate(); List certificates = new ArrayList<>(); certificate.setTenantId(tenantId); + certificate.setDeviceIdentifier(commonName); certificate.setCertificate(issuedCert); certificates.add(certificate); saveCertInKeyStore(certificates); diff --git a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql index 0fb769e406..bee98d7dbf 100644 --- a/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql +++ b/components/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.core/src/test/resources/sql/h2.sql @@ -39,5 +39,5 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( TENANT_ID INTEGER DEFAULT 0, DEVICE_IDENTIFIER VARCHAR(300), USERNAME VARCHAR(500) DEFAULT NULL, - PRIMARY KEY (ID) + PRIMARY KEY (ID) ); \ No newline at end of file diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index b218c20dd4..08506aab76 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml index 6bed168fde..54ab94e0c2 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml index 66530f647c..3203b5510b 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml index d4c7eda985..ef1768fbd2 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger/pom.xml @@ -21,7 +21,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml index 90a6331adb..c23c06b599 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.pull.notification/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index e5b71633c3..7c985635cb 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml index b3fabbd1a3..06b1fa73a9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index 44fac89fc6..2ac7d3c3bf 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index 5a27316b32..8051a35eb4 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml index 173081ceff..02f15f077f 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml new file mode 100644 index 0000000000..808841bd4b --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml @@ -0,0 +1,212 @@ + + + + + + + device-mgt-extensions + io.entgra.device.mgt.core + 5.0.33-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper + bundle + Entgra IoT - User store role mapping Module + Entgra IoT - User store role mapping Module + http://entgra.io + + + + + org.apache.felix + maven-scr-plugin + + + maven-compiler-plugin + + 1.8 + 1.8 + + 2.3.2 + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${io.entgra.device.mgt.core.version} + IOT - User store role mapping Module + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal + + 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, + org.wso2.carbon.utils.*, + javax.xml.bind;resolution:=optional, + javax.xml.bind.annotation, + javax.xml.parsers, + org.w3c.dom, + org.wso2.carbon, + org.wso2.carbon.context, + org.wso2.carbon.user.api, + org.wso2.carbon.user.core.common, + org.wso2.carbon.user.core.service, + org.wso2.carbon.user.mgt.common, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service, + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception + + + !io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal, + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.*;version="${project.version}" + + + + + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + + + + + + + + + + + + + + org.wso2.carbon + org.wso2.carbon.core + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + org.wso2.carbon + org.wso2.carbon.user.api + provided + + + org.wso2.carbon + org.wso2.carbon.user.core + provided + + + org.wso2.carbon.identity.framework + org.wso2.carbon.user.mgt + provided + + + org.mockito + mockito-inline + test + + + org.testng + testng + test + + + org.wso2.orbit.com.h2database + h2 + test + + + org.apache.httpcomponents.wso2 + httpcore + test + + + org.wso2.apache.httpcomponents + httpclient + test + + + org.wso2.carbon + org.wso2.carbon.securevault + test + + + org.wso2.securevault + org.wso2.securevault + test + + + xerces.wso2 + xercesImpl + test + + + org.apache.axis2.wso2 + axis2 + test + + + org.wso2.carbon + org.wso2.carbon.queuing + test + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.server.bootup.heartbeat.beacon + provided + + + diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMapper.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMapper.java new file mode 100644 index 0000000000..59e3d352c7 --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMapper.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper; + +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.bean.RoleMapping; +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.bean.UserStoreRoleMappingConfig; +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal.UserStoreRoleMappingDataHolder; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +public class UserStoreRoleMapper implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(UserStoreRoleMapper.class); + + private UserStoreRoleMappingConfig config = null; + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + + config = UserStoreRoleMappingDataHolder.getInstance() + .getUserStoreRoleMappingConfigManager().getUserStoreRoleMappingConfig(); + + try { + if ((config.isEnabled() && + UserStoreRoleMappingDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled() && + UserStoreRoleMappingDataHolder.getInstance().getHeartBeatService().isQualifiedToExecuteTask()) + || (config.isEnabled() && + !UserStoreRoleMappingDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled())) { + Runnable periodicTask = new Runnable() { + public void run() { + updateRoleMapping(); + log.info("UserStoreRoleMapper executed...."); + } + }; + + ScheduledExecutorService executor = + Executors.newSingleThreadScheduledExecutor(); + + executor.scheduleAtFixedRate(periodicTask, config.getInitialDelayInSeconds(), config.getPeriodInSeconds(), TimeUnit.SECONDS); + } + } catch (HeartBeatManagementException e) { + log.error("Error while accessing heart beat service " + e.getMessage()); + } + } + + private void updateRoleMapping() { + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( + MultitenantConstants.SUPER_TENANT_ID); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + + List roleMappings = config.getMappings(); + + if (!roleMappings.isEmpty()) { + UserStoreManager userStoreManager = + UserStoreRoleMappingDataHolder.getInstance().getRealmService() + .getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getUserStoreManager(); + + for (RoleMapping mapping : roleMappings) { + if (userStoreManager.isExistingRole(mapping.getSecondaryRole())) { + String[] users = userStoreManager.getUserListOfRole(mapping.getSecondaryRole()); + if (users != null && users.length > 0) { + List primaryRoles = mapping.getInternalRoles(); + for (String role : primaryRoles) { + if (userStoreManager.isExistingRole(role)) { + String[] existingUsers = userStoreManager.getUserListOfRole(role); + List existingUserList = new ArrayList<>(Arrays.asList(existingUsers)); + List newUserList = new ArrayList<>(); + for (String user : users) { + if (existingUserList.contains(user)) { + // if contains, remove from existing list + existingUserList.remove(user); + } else { + // new user + newUserList.add(user); + } + } + + List deleteUserList = new ArrayList<>(); + if (!existingUserList.isEmpty()) { + String domain = mapping.getSecondaryRole().substring(0, mapping.getSecondaryRole().indexOf("/")); + for (String user : existingUserList) { + if (user.startsWith(domain.toUpperCase())) { + deleteUserList.add(user); + } + } + } + + // update user list of given role + if (!newUserList.isEmpty() || !deleteUserList.isEmpty()) { + userStoreManager.updateUserListOfRole(role, deleteUserList.toArray(new String[0]), newUserList.toArray(new String[0])); + log.info("update user role mapping executed....."); + } + } + } + } + } + } + } + } catch (UserStoreException e) { + log.error("Error while getting user store..." + e.getMessage()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMappingConfigManager.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMappingConfigManager.java new file mode 100644 index 0000000000..1c4b5eac16 --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/UserStoreRoleMappingConfigManager.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper; + +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.bean.UserStoreRoleMappingConfig; +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.exception.UserStoreRoleMapperException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; + +public class UserStoreRoleMappingConfigManager { + + private static final Log log = LogFactory.getLog(UserStoreRoleMappingConfigManager.class); + private static final String USERSTORE_ROLE_MAPPING_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + + File.separator + "user-store-role-mapping-config.xml"; + + private final UserStoreRoleMappingConfig userStoreRoleMappingConfig; + + public UserStoreRoleMappingConfigManager() throws UserStoreRoleMapperException { + try { + File UserStoreRoleMappingConfig = new File(USERSTORE_ROLE_MAPPING_CONFIG_PATH); + Document doc = convertToDocument(UserStoreRoleMappingConfig); + JAXBContext smsContext = JAXBContext.newInstance(UserStoreRoleMappingConfig.class); + Unmarshaller unmarshaller = smsContext.createUnmarshaller(); + this.userStoreRoleMappingConfig = (UserStoreRoleMappingConfig) unmarshaller.unmarshal(doc); + } catch (JAXBException e) { + String msg = "Error occurred while initializing config '" + USERSTORE_ROLE_MAPPING_CONFIG_PATH + "'"; + log.error(msg, e); + throw new UserStoreRoleMapperException(msg, e); + } + } + + private static Document convertToDocument(File file) throws UserStoreRoleMapperException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + + try { + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new UserStoreRoleMapperException("Error occurred while parsing " + USERSTORE_ROLE_MAPPING_CONFIG_PATH + + " file, while converting to a org.w3c.dom.Document", e); + } + } + + public UserStoreRoleMappingConfig getUserStoreRoleMappingConfig() { + return this.userStoreRoleMappingConfig; + } + +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/RoleMapping.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/RoleMapping.java new file mode 100644 index 0000000000..604c58b4a2 --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/RoleMapping.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper.bean; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement( + name = "mapping" +) +public class RoleMapping { + private String secondaryRole; + + private List internalRoles; + + @XmlAttribute( + name = "secondaryRole" + ) + public String getSecondaryRole() { + return secondaryRole; + } + + public void setSecondaryRole(String secondaryRole) { + this.secondaryRole = secondaryRole; + } + + @XmlElementWrapper( + name = "internalRoles" + ) + @XmlElement( + name = "role" + ) + public List getInternalRoles() { + return internalRoles; + } + + public void setInternalRoles(List internalRoles) { + this.internalRoles = internalRoles; + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/UserStoreRoleMappingConfig.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/UserStoreRoleMappingConfig.java new file mode 100644 index 0000000000..58e287a9ee --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/bean/UserStoreRoleMappingConfig.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement( + name = "UserStoreRoleMappingConfig" +) +public class UserStoreRoleMappingConfig { + + private boolean enabled; + private List mappings; + + private long initialDelayInSeconds; + + private long periodInSeconds; + + @XmlElement( + name = "enabled" + ) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @XmlElementWrapper( + name = "mappings" + ) + @XmlElement( + name = "mapping" + ) + public List getMappings() { + return mappings; + } + + public void setMappings(List mappings) { + this.mappings = mappings; + } + + @XmlElement( + name = "initialDelayInSeconds" + ) + public long getInitialDelayInSeconds() { + return initialDelayInSeconds; + } + + public void setInitialDelayInSeconds(long initialDelayInSeconds) { + this.initialDelayInSeconds = initialDelayInSeconds; + } + + @XmlElement( + name = "periodInSeconds" + ) + public long getPeriodInSeconds() { + return periodInSeconds; + } + + public void setPeriodInSeconds(long periodInSeconds) { + this.periodInSeconds = periodInSeconds; + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/exception/UserStoreRoleMapperException.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/exception/UserStoreRoleMapperException.java new file mode 100644 index 0000000000..72d56d202a --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/exception/UserStoreRoleMapperException.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper.exception; + +public class UserStoreRoleMapperException extends Exception { + + public UserStoreRoleMapperException(String msg, Exception e) { + super(msg, e); + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingDataHolder.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingDataHolder.java new file mode 100644 index 0000000000..71d3c32edd --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingDataHolder.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal; + +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.UserStoreRoleMappingConfigManager; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.utils.ConfigurationContextService; + +public class UserStoreRoleMappingDataHolder { + + private ConfigurationContextService configurationContextService; + private RealmService realmService; + private UserStoreRoleMappingConfigManager userStoreRoleMappingConfigManager; + private HeartBeatManagementService heartBeatService; + private static final UserStoreRoleMappingDataHolder thisInstance = new UserStoreRoleMappingDataHolder(); + + private UserStoreRoleMappingDataHolder() {} + + public static UserStoreRoleMappingDataHolder getInstance() { + return thisInstance; + } + + public ConfigurationContextService getConfigurationContextService() { + return configurationContextService; + } + + public void setConfigurationContextService(ConfigurationContextService configurationContextService) { + this.configurationContextService = configurationContextService; + } + + public UserStoreManager getUserStoreManager() throws UserStoreException { + if (realmService == null) { + String msg = "Realm service has not initialized."; + throw new IllegalStateException(msg); + } + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } + + public UserRealm getUserRealm() throws UserStoreException { + UserRealm realm; + if (realmService == null) { + throw new IllegalStateException("Realm service not initialized"); + } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + realm = realmService.getTenantUserRealm(tenantId); + return realm; + } + + public RealmService getRealmService() { + return realmService; + } + + public void setRealmService(RealmService realmService) { + this.realmService = realmService; + } + + public UserStoreRoleMappingConfigManager getUserStoreRoleMappingConfigManager() { + return userStoreRoleMappingConfigManager; + } + + public void setUserStoreRoleMappingConfigManager(UserStoreRoleMappingConfigManager userStoreRoleMappingConfigManager) { + this.userStoreRoleMappingConfigManager = userStoreRoleMappingConfigManager; + } + + public HeartBeatManagementService getHeartBeatService() { + return heartBeatService; + } + + public void setHeartBeatService(HeartBeatManagementService heartBeatService) { + this.heartBeatService = heartBeatService; + } +} diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java new file mode 100644 index 0000000000..2471c18403 --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/userstore/role/mapper/internal/UserStoreRoleMappingServiceComponent.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal; + +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.UserStoreRoleMapper; +import io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.UserStoreRoleMappingConfigManager; +import io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +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.core.ServerStartupObserver; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.utils.ConfigurationContextService; + +/** + * @scr.component name="io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal.UserStoreRoleMappingServiceComponent" + * immediate="true" + * @scr.reference name="user.realmservice.default" + * interface="org.wso2.carbon.user.core.service.RealmService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRealmService" + * unbind="unsetRealmService" + * @scr.reference name="config.context.service" + * interface="org.wso2.carbon.utils.ConfigurationContextService" + * cardinality="0..1" + * policy="dynamic" + * bind="setConfigurationContextService" + * unbind="unsetConfigurationContextService" + * @scr.reference name="entgra.heart.beat.service" + * interface="io.entgra.device.mgt.core.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" + * cardinality="0..1" + * policy="dynamic" + * bind="setHeartBeatService" + * unbind="unsetHeartBeatService" + */ +public class UserStoreRoleMappingServiceComponent { + + private static final Log log = LogFactory.getLog(UserStoreRoleMappingServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Role Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + UserStoreRoleMapper mapper = new UserStoreRoleMapper(); + bundleContext.registerService(ServerStartupObserver.class.getName(), mapper, null); + UserStoreRoleMappingDataHolder.getInstance().setUserStoreRoleMappingConfigManager(new UserStoreRoleMappingConfigManager()); + if (log.isDebugEnabled()) { + log.debug("Role Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Role Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Role Manager Service Component"); + } + } + + protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + + UserStoreRoleMappingDataHolder.getInstance().setConfigurationContextService(configurationContextService); + } + + protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + UserStoreRoleMappingDataHolder.getInstance().setConfigurationContextService(null); + } + + /** + * Sets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + UserStoreRoleMappingDataHolder.getInstance().setRealmService(realmService); + } + + /** + * Unsets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + UserStoreRoleMappingDataHolder.getInstance().setRealmService(null); + } + + @SuppressWarnings("unused") + protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { + if (log.isDebugEnabled()) { + log.debug("Setting heart beat service"); + } + UserStoreRoleMappingDataHolder.getInstance().setHeartBeatService(heartBeatService); + } + + @SuppressWarnings("unused") + protected void unsetHeartBeatService(HeartBeatManagementService heartBeatManagementService) { + if (log.isDebugEnabled()) { + log.debug("Removing heart beat service"); + } + UserStoreRoleMappingDataHolder.getInstance().setHeartBeatService(null); + } +} diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 6fce15dac4..242c96ae81 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml @@ -43,6 +43,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.logger io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager io.entgra.device.mgt.core.device.mgt.extensions.stateengine + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml index d5bbb2e967..c54c9445d3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java index 7e645198a6..39b133202a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/ActivityInfoProviderService.java @@ -378,7 +378,7 @@ public interface ActivityInfoProviderService { tags = "Device Activity Info Provider", extensions = { @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity") + @ExtensionProperty(name = Constants.SCOPE, value = "dm:activity:get") }) }, nickname = "getDeviceActivitiesWithFilters" diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java index c42557b7df..52f10eb16b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/DeviceManagementService.java @@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api; import io.entgra.device.mgt.core.apimgt.annotations.Scope; import io.entgra.device.mgt.core.apimgt.annotations.Scopes; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.*; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants; import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; @@ -33,11 +34,30 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.monitor.NonComplianceData; import io.entgra.device.mgt.core.device.mgt.common.search.PropertyMap; import io.entgra.device.mgt.core.device.mgt.common.search.SearchContext; -import io.swagger.annotations.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +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.List; @@ -1255,6 +1275,49 @@ public interface DeviceManagementService { @Size(max = 45) String deviceId); + @PUT + @Produces(MediaType.APPLICATION_JSON) + @Path("/disenroll") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Remove Multiple Devices Specified by Device IDs and Device Type", + notes = "Deletes multiple devices of the specified device type specified by their device IDs" + + " and returns the status of the dis-enrollment operation.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:delete") + }) + }, + nickname = "deleteMultipleDevicesByType" + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully deleted the devices.", + response = Device.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while deleting devices.", + response = ErrorResponse.class) + }) + Response disenrollMultipleDevices(@ApiParam( + name = "deviceTypeWithDeviceIds", + value = "Device type and corresponding device IDs for disenrollment", + required = true) + DisenrollRequest deviceTypeWithDeviceIds); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/device-type/{type}/features") diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java index b8a3c1e528..8d25b43a95 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/UserManagementService.java @@ -116,7 +116,7 @@ import javax.ws.rs.core.Response; description = "Adding a User", key = "um:users:cred:change", roles = {"Internal/devicemgt-user"}, - permissions = {"/login/password/update"} + permissions = {"/device-mgt/users/password/update"} ), @Scope( name = "Sending Enrollment Invitations to Users", diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java index de206daf85..96e3919929 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -20,22 +20,32 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderServiceImpl; +import io.entgra.device.mgt.core.apimgt.application.extension.dto.ApiApplicationKey; +import io.entgra.device.mgt.core.apimgt.application.extension.exception.APIManagerException; +import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; +import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil; +import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.util.DisenrollRequest; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.DCRResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenResponse; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; -import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; @@ -101,8 +111,9 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; -import java.util.concurrent.ExecutionException; +import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ExecutionException; @Path("/devices") public class DeviceManagementServiceImpl implements DeviceManagementService { @@ -474,6 +485,64 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } + @PUT + @Override + @Path("/disenroll") + public Response disenrollMultipleDevices(DisenrollRequest deviceTypeWithDeviceIds) { + + if (deviceTypeWithDeviceIds == null) { + String errorMsg = "Invalid request. The request body must not be null."; + return Response.status(Response.Status.BAD_REQUEST).entity(errorMsg).build(); + } + DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); + + List successfullyDisenrolledDevices = new ArrayList<>(); + List failedToDisenrollDevices = new ArrayList<>(); + + Map> list = deviceTypeWithDeviceIds.getDeviceTypeWithDeviceIds(); + String deviceType; + List deviceIds; + DeviceIdentifier deviceIdentifier; + Device persistedDevice; + boolean response; + + for (Map.Entry> entry : list.entrySet()) { + deviceType = entry.getKey(); + deviceIds = entry.getValue(); + + for (String deviceId : deviceIds) { + deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); + try { + persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, true); + if (persistedDevice != null) { + response = deviceManagementProviderService.disenrollDevice(deviceIdentifier); + if (response) { + successfullyDisenrolledDevices.add(deviceIdentifier); + } else { + failedToDisenrollDevices.add(deviceIdentifier); + } + } else { + failedToDisenrollDevices.add(deviceIdentifier); + if(log.isDebugEnabled()){ + String msg = "Error encountered while dis-enrolling device of type: " + deviceType + " with " + deviceId; + log.error(msg); + } + } + } catch (DeviceManagementException e) { + String msg = "Error encountered while dis-enrolling device of type: " + deviceType + " with " + deviceId; + log.error(msg, e); + failedToDisenrollDevices.add(deviceIdentifier); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + } + + Map> responseMap = new HashMap<>(); + responseMap.put("successfullyDisenrollDevices", successfullyDisenrolledDevices); + responseMap.put("failedToDisenrollDevices", failedToDisenrollDevices); + + return Response.status(Response.Status.OK).entity(responseMap).build(); + } @POST @Override @Path("/type/{deviceType}/id/{deviceId}/rename") @@ -819,10 +888,46 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { KeyMgtService keyMgtService = new KeyMgtServiceImpl(); try { - DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username, - "client_credentials", null, new String[] {"device_management"}, false, validityTime); - deviceConfig.setClientId(dcrResponse.getClientId()); - deviceConfig.setClientSecret(dcrResponse.getClientSecret()); + //todo - lasantha - can't get password from here + ApiApplicationKey apiApplicationKey; + try { + APIApplicationServices apiApplicationServices = DeviceMgtAPIUtils.getApiApplicationServices(); + APIApplicationKey adminDCRResponse = apiApplicationServices.createAndRetrieveApplicationCredentials( + "ClientForJWTTokenGeneration", + "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer" + ); + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = (JWTClientManagerService) ctx. + getOSGiService(JWTClientManagerService.class, null); + JWTClient jwtClient = jwtClientManagerService.getJWTClient(); + AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(adminDCRResponse.getClientId(), + adminDCRResponse.getClientSecret(), + username, "appm:subscribe apim:admin apim:api_key apim:app_import_export apim:app_manage" + + " apim:store_settings apim:sub_alert_manage apim:sub_manage apim:subscribe openid perm:device:enroll " + + "perm:devices:details perm:devices:features perm:devices:search perm:devices:view perm:groups:groups " + + "perm:users:send-invitation"); + + APIManagementProviderService apiManagementProviderService = DeviceMgtAPIUtils.getAPIManagementService(); + apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName, + new String[] {"device_management"}, "PRODUCTION", null, false, String.valueOf(validityTime), + null, accessTokenInfo.getAccessToken(), null, null,true); + + } catch (JWTClientException e) { + String msg = "Error while generating an application tokens for Tenant Admin."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (APIServicesException e) { + String msg = "Error while generating api Application"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + + //todo call REST APIs + deviceConfig.setClientId(apiApplicationKey.getConsumerKey()); + deviceConfig.setClientSecret(apiApplicationKey.getConsumerSecret()); StringBuilder scopes = new StringBuilder("device:" + type.replace(" ", "") + ":" + id); for (String topic : mqttEventTopicStructure) { @@ -840,7 +945,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation"); - TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(), + TokenRequest tokenRequest = new TokenRequest(apiApplicationKey.getConsumerKey(), + apiApplicationKey.getConsumerSecret(), null, scopes.toString(), "client_credentials", null, null, null, null, validityTime); TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest); @@ -870,6 +976,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (APIManagerException e) { + String msg = "Error while calling rest Call for application key generation"; + log.error(msg, e); } return Response.status(Response.Status.OK).entity(deviceConfig).build(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java index a80665d294..7790b5f913 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -691,7 +691,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if ((filter == null) || filter.isEmpty()) { filter = "*"; } else { - filter += "*"; + filter = "*" + filter + "*"; } if (log.isDebugEnabled()) { log.debug("Getting the list of user roles"); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java index 10b5a29dfe..bc8b595ce8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/UserManagementServiceImpl.java @@ -449,7 +449,7 @@ public class UserManagementServiceImpl implements UserManagementService { try { if (StringUtils.isNotEmpty(username)) { - commonUsers = getUserList(null, username); + commonUsers = getUserList(null, "*" + username + "*"); } if (commonUsers != null) { commonUsers.remove(Constants.APIM_RESERVED_USER); @@ -457,7 +457,7 @@ public class UserManagementServiceImpl implements UserManagementService { } if (!skipSearch(commonUsers) && StringUtils.isNotEmpty(firstName)) { - tempList = getUserList(Constants.USER_CLAIM_FIRST_NAME, firstName); + tempList = getUserList(Constants.USER_CLAIM_FIRST_NAME, "*" + firstName + "*"); if (commonUsers == null) { commonUsers = tempList; } else { @@ -466,7 +466,7 @@ public class UserManagementServiceImpl implements UserManagementService { } if (!skipSearch(commonUsers) && StringUtils.isNotEmpty(lastName)) { - tempList = getUserList(Constants.USER_CLAIM_LAST_NAME, lastName); + tempList = getUserList(Constants.USER_CLAIM_LAST_NAME, "*" + lastName + "*"); if (commonUsers == null || commonUsers.size() == 0) { commonUsers = tempList; } else { @@ -475,7 +475,7 @@ public class UserManagementServiceImpl implements UserManagementService { } if (!skipSearch(commonUsers) && StringUtils.isNotEmpty(emailAddress)) { - tempList = getUserList(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress); + tempList = getUserList(Constants.USER_CLAIM_EMAIL_ADDRESS, "*" + emailAddress + "*"); if (commonUsers == null || commonUsers.size() == 0) { commonUsers = tempList; } else { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/DisenrollRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/DisenrollRequest.java new file mode 100644 index 0000000000..026866b5e1 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/util/DisenrollRequest.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.api.jaxrs.service.impl.util; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; +import java.util.Map; + +@ApiModel(value = "DisenrollRequest", description = "Contains the multiple devices specified by device IDs") +public class DisenrollRequest { + @ApiModelProperty(name = "deviceTypeWithDeviceIds", value = "Contains the multiple devices specified by device IDs with type", + required = true) + private Map> deviceTypeWithDeviceIds; + + public Map> getDeviceTypeWithDeviceIds() { + return deviceTypeWithDeviceIds; + } + + public void setDeviceTypeWithDeviceIds(Map> deviceTypeWithDeviceIds) { + this.deviceTypeWithDeviceIds = deviceTypeWithDeviceIds; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java index 7b52ddd57c..5494476636 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java @@ -19,6 +19,9 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; +import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.DeviceTypeVersionWrapper; @@ -155,7 +158,9 @@ public class DeviceMgtAPIUtils { private static volatile SubscriptionManager subscriptionManager; private static volatile ApplicationManager applicationManager; - + private static volatile APIApplicationServices apiApplicationServices; + private static volatile ConsumerRESTAPIServices consumerRESTAPIServices; + private static volatile APIManagementProviderService apiManagementProviderService; private static volatile APIPublisherService apiPublisher; static { @@ -408,6 +413,63 @@ public class DeviceMgtAPIUtils { return otpManagementService; } + /** + * Initializing and accessing method for APIM Consumer REST API. + * + * @return ConsumerRESTAPIServices instance + * @throws IllegalStateException if ConsumerRESTAPIServices cannot be initialized + */ + public static synchronized ConsumerRESTAPIServices getConsumerRESTAPIServices() { + if (consumerRESTAPIServices == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + consumerRESTAPIServices = (ConsumerRESTAPIServices) ctx.getOSGiService(ConsumerRESTAPIServices.class, null); + if (consumerRESTAPIServices == null) { + String msg = "Consumer Rest API service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return consumerRESTAPIServices; + } + + /** + * Initializing and accessing method for APIM API application REST API. + * + * @return APIApplicationServices instance + * @throws IllegalStateException if APIApplicationServices cannot be initialized + */ + public static synchronized APIApplicationServices getApiApplicationServices() { + if (apiApplicationServices == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + apiApplicationServices = (APIApplicationServices) ctx.getOSGiService(APIApplicationServices.class, null); + if (apiApplicationServices == null) { + String msg = "API application service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return apiApplicationServices; + } + + /** + * Initializing and accessing method for API management Provider Service. + * + * @return APIManagementProviderService instance + * @throws IllegalStateException if APIManagementProviderService cannot be initialized + */ + public static synchronized APIManagementProviderService getAPIManagementService() { + if (apiManagementProviderService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + apiManagementProviderService = (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null); + if (apiManagementProviderService == null) { + String msg = "API Management Provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return apiManagementProviderService; + } + public static RegistryService getRegistryService() { RegistryService registryService; PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml index ca51d3e198..b2639eebd1 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/pom.xml @@ -21,7 +21,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/spi/DeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/spi/DeviceManagementService.java index d847fd8f9b..b7cd91f34e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/spi/DeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/spi/DeviceManagementService.java @@ -26,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringManager; import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; /** @@ -65,4 +66,6 @@ public interface DeviceManagementService { DeviceEnrollmentInvitationDetails getDeviceEnrollmentInvitationDetails(); License getLicenseConfig(); + + DeviceTypeMetaDefinition getDeviceTypeMetaDefinition(); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java index 7f14f5241b..2a24f97e42 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java @@ -41,6 +41,8 @@ public class DeviceTypeMetaDefinition { private boolean longLivedToken = false; + private boolean storeVisibilityEnabled = true; + public String getDescription() { return description; } @@ -121,4 +123,12 @@ public class DeviceTypeMetaDefinition { public void setLongLivedToken(boolean longLivedToken) { this.longLivedToken = longLivedToken; } + + public boolean isStoreVisibilityEnabled() { + return storeVisibilityEnabled; + } + + public void setStoreVisibilityEnabled(boolean storeVisibilityEnabled) { + this.storeVisibilityEnabled = storeVisibilityEnabled; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDetails.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDetails.java new file mode 100644 index 0000000000..4084b93245 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/type/mgt/DeviceTypeMetaDetails.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2018 - 2023, 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.device.mgt.core.device.mgt.common.type.mgt; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DeviceTypeMetaDetails", propOrder = { + "storeVisibilityEnabled" +}) +public class DeviceTypeMetaDetails { + + @XmlElement(name = "storeVisibilityEnabled") + private boolean storeVisibilityEnabled; + + public boolean isStoreVisibilityEnabled() { + return storeVisibilityEnabled; + } + + public void setStoreVisibilityEnabled(boolean storeVisibilityEnabled) { + this.storeVisibilityEnabled = storeVisibilityEnabled; + } +} + + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml index 9f2d5aa52b..c4ad6ed771 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml index f8d7331ef1..4739b10c05 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java index f2bccac8e7..9f58717c7d 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/DeviceManagementPluginRepository.java @@ -85,7 +85,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis if (isInitiated) { /* Initializing Device Management Service Provider */ provider.init(); - DeviceTypeMetaDefinition deviceTypeDefinition = null; + DeviceTypeMetaDefinition deviceTypeDefinition; if (provider instanceof DeviceTypeDefinitionProvider) { DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier( provider.getType()); @@ -102,6 +102,8 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis if (existingProvider != null) { removeDeviceManagementProvider(provider); } + } else { + deviceTypeDefinition = provider.getDeviceTypeMetaDefinition(); } DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants, deviceTypeDefinition); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java index ca73829320..1b4f09b7e5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGeofenceDAOImpl.java @@ -142,7 +142,7 @@ public abstract class AbstractGeofenceDAOImpl implements GeofenceDAO { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(index++, tenantId); if (isNameProvided) { - stmt.setString(index++, request.getProperty(DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); + stmt.setString(index++, "%" + request.getProperty(DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); } stmt.setInt(index++, request.getRowCount()); stmt.setInt(index, request.getStartIndex()); @@ -179,7 +179,7 @@ public abstract class AbstractGeofenceDAOImpl implements GeofenceDAO { "WHERE FENCE_NAME LIKE ?" + "AND TENANT_ID = ? "; try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, fenceName + "%"); + stmt.setString(1, "%" + fenceName + "%"); stmt.setInt(2, tenantId); try (ResultSet rst = stmt.executeQuery()) { geofenceData = extractGeofenceData(rst); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index a09f74a354..40a785a639 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device; import io.entgra.device.mgt.core.device.mgt.common.Count; import io.entgra.device.mgt.core.device.mgt.common.Device; +import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo; import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo; import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException; @@ -31,7 +32,11 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -1467,4 +1472,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { return geoClusters; } */ + + @Override + public void refactorDeviceStatus(Connection conn, List validDevices) throws DeviceManagementDAOException { + String updateQuery = "UPDATE DM_DEVICE_STATUS SET STATUS = ? WHERE ID = ?"; + String selectLastMatchingRecordQuery = "SELECT TOP 1 ID FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? AND DEVICE_ID = ? ORDER BY ID DESC"; + + try (PreparedStatement selectStatement = conn.prepareStatement(selectLastMatchingRecordQuery); + PreparedStatement updateStatement = conn.prepareStatement(updateQuery)) { + + for (Device device : validDevices) { + + selectStatement.setInt(1, device.getEnrolmentInfo().getId()); + selectStatement.setInt(2, device.getId()); + + ResultSet resultSet = selectStatement.executeQuery(); + int lastRecordId = 0; + if (resultSet.next()) { + lastRecordId = resultSet.getInt("ID"); + } + + updateStatement.setString(1, String.valueOf(EnrolmentInfo.Status.DELETED)); + updateStatement.setInt(2, lastRecordId); + updateStatement.execute(); + } + + } catch (SQLException e) { + String msg = "SQL error occurred while updating device status properties."; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java index 404129598a..d0e955dec5 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/GenericGeofenceDAOImpl.java @@ -142,7 +142,7 @@ public class GenericGeofenceDAOImpl extends AbstractGeofenceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(index++, tenantId); if (isNameProvided) { - stmt.setString(index++, request.getProperty(DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); + stmt.setString(index++, request.getProperty("%" + DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); } stmt.setInt(index++, request.getRowCount()); stmt.setInt(index, request.getStartIndex()); @@ -179,7 +179,7 @@ public class GenericGeofenceDAOImpl extends AbstractGeofenceDAOImpl { "WHERE FENCE_NAME LIKE ?" + "AND TENANT_ID = ? "; try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, fenceName + "%"); + stmt.setString(1,"%" + fenceName + "%"); stmt.setInt(2, tenantId); try (ResultSet rst = stmt.executeQuery()) { geofenceData = extractGeofenceData(rst); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/SQLServerGeofenceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/SQLServerGeofenceDAOImpl.java index fa04264286..c1a719f446 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/SQLServerGeofenceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/geofence/SQLServerGeofenceDAOImpl.java @@ -71,7 +71,7 @@ public class SQLServerGeofenceDAOImpl extends AbstractGeofenceDAOImpl { try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(index++, tenantId); if (isNameProvided) { - stmt.setString(index++, request.getProperty(DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); + stmt.setString(index++, "%" + request.getProperty(DeviceManagementConstants.GeoServices.FENCE_NAME).toString() + "%"); } stmt.setInt(index++, request.getStartIndex()); stmt.setInt(index, request.getRowCount()); @@ -166,4 +166,48 @@ public class SQLServerGeofenceDAOImpl extends AbstractGeofenceDAOImpl { throw new DeviceManagementDAOException(msg, e); } } + + @Override + public List getGeoFences(int groupId, int tenantId) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + String sql = "SELECT " + + "G.ID AS FENCE_ID, " + + "FENCE_NAME, " + + "DESCRIPTION, " + + "LATITUDE, " + + "LONGITUDE, " + + "RADIUS, " + + "GEO_JSON, " + + "FENCE_SHAPE " + + "FROM DM_GEOFENCE G " + + "JOIN DM_GEOFENCE_GROUP_MAPPING M ON G.ID = M.FENCE_ID " + + "WHERE M.GROUP_ID = ? AND TENANT_ID = ?"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + ResultSet rst = stmt.executeQuery(); + List geofenceDataList = new ArrayList<>(); + while (rst.next()) { + GeofenceData geofenceData = new GeofenceData(); + geofenceData.setId(rst.getInt("FENCE_ID")); + geofenceData.setFenceName(rst.getString("FENCE_NAME")); + geofenceData.setDescription(rst.getString("DESCRIPTION")); + geofenceData.setLatitude(rst.getDouble("LATITUDE")); + geofenceData.setLongitude(rst.getDouble("LONGITUDE")); + geofenceData.setRadius(rst.getFloat("RADIUS")); + geofenceData.setGeoJson(rst.getString("GEO_JSON")); + geofenceData.setFenceShape(rst.getString("FENCE_SHAPE")); + geofenceDataList.add(geofenceData); + } + return geofenceDataList; + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving Geo fences of group " + groupId + + " and tenant " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java index 2f690b8869..a1abfa987e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/operation/mgt/dao/impl/ConfigOperationMSSQLDAOImpl.java @@ -24,11 +24,21 @@ import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ConfigOperati import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.Operation; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.io.*; -import java.sql.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -43,7 +53,7 @@ public class ConfigOperationMSSQLDAOImpl extends GenericOperationDAOImpl { operation.setCreatedTimeStamp(new Timestamp(new Date().getTime()).toString()); Connection connection = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, " + - "INITIATED_BY, OPERATION_DETAILS) VALUES (?, ?, ?, ?, ?, ?)"; + "INITIATED_BY, OPERATION_DETAILS, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement stmt = connection.prepareStatement(sql, new String[]{"id"})) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); @@ -55,6 +65,7 @@ public class ConfigOperationMSSQLDAOImpl extends GenericOperationDAOImpl { stmt.setString(4, operation.getCode()); stmt.setString(5, operation.getInitiatedBy()); stmt.setBytes(6, operationBytes); + stmt.setInt(7, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { int id = -1; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManagementService.java index 516159d597..0df3bdad7e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/java/io/entgra/device/mgt/core/device/mgt/core/TestDeviceManagementService.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringMa import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; import java.util.ArrayList; @@ -135,4 +136,9 @@ public class TestDeviceManagementService implements DeviceManagementService { } @Override public License getLicenseConfig() { return null; } + + @Override + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return null; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml index 093a8444d6..f5065bbeb4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java index 0eeab6f0f9..eb03f93334 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java @@ -17,13 +17,18 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManager; +import io.entgra.device.mgt.core.device.mgt.common.DeviceStatusTaskPluginConfig; import io.entgra.device.mgt.core.device.mgt.common.InitialOperationConfig; +import io.entgra.device.mgt.core.device.mgt.common.MonitoringOperation; +import io.entgra.device.mgt.core.device.mgt.common.OperationMonitoringTaskConfig; import io.entgra.device.mgt.core.device.mgt.common.ProvisioningConfig; -import io.entgra.device.mgt.core.device.mgt.common.*; +import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDetails; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManager; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry; import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration; -import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.general.GeneralConfig; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails; import io.entgra.device.mgt.core.device.mgt.common.license.mgt.License; @@ -31,6 +36,7 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringMa import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.Feature; import io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config.*; @@ -70,6 +76,7 @@ public class DeviceTypeManagerService implements DeviceManagementService { private DeviceTypePlatformDetails deviceTypePlatformDetails; private DeviceEnrollmentInvitationDetails deviceEnrollmentInvitationDetails; private GeneralConfig generalConfig; + private DeviceTypeMetaDefinition deviceTypeMetaDefinition; private boolean isRegistryBasedConfigs = false; private boolean isScheduled = false; private String notifierType; @@ -97,6 +104,8 @@ public class DeviceTypeManagerService implements DeviceManagementService { this.setDeviceEnrollmentInvitationDetails(deviceTypeConfiguration); this.licenseConfig = new License(); this.setLicenseConfig(deviceTypeConfiguration); + this.deviceTypeMetaDefinition = new DeviceTypeMetaDefinition(); + this.setDeviceTypeMetaDefinition(deviceTypeConfiguration); } @Override @@ -250,6 +259,11 @@ public class DeviceTypeManagerService implements DeviceManagementService { return licenseConfig; } + @Override + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return deviceTypeMetaDefinition; + } + private void setProvisioningConfig(String tenantDomain, DeviceTypeConfiguration deviceTypeConfiguration) { if (deviceTypeConfiguration.getProvisioningConfig() != null) { boolean sharedWithAllTenants = deviceTypeConfiguration.getProvisioningConfig().isSharedWithAllTenants(); @@ -377,4 +391,11 @@ public class DeviceTypeManagerService implements DeviceManagementService { licenseConfig.setText(license.getText()); } } + + public void setDeviceTypeMetaDefinition(DeviceTypeConfiguration deviceTypeConfiguration) { + DeviceTypeMetaDetails deviceTypeMetaDefinitions = deviceTypeConfiguration.getDeviceTypeMetaDetails(); + if (deviceTypeMetaDefinitions != null) { + deviceTypeMetaDefinition.setStoreVisibilityEnabled(deviceTypeMetaDefinitions.isStoreVisibilityEnabled()); + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java index 58e0cd6021..b15c2f3c88 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.extensions.device.type.template.config; import io.entgra.device.mgt.core.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitationDetails; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDetails; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; import javax.xml.bind.annotation.*; @@ -88,6 +89,8 @@ public class DeviceTypeConfiguration { protected DeviceTypePlatformDetails deviceTypePlatformDetails; @XmlElement(name = "DeviceEnrollmentInvitationDetails", required = true) protected DeviceEnrollmentInvitationDetails deviceEnrollmentInvitationDetails; + @XmlElement(name = "DeviceTypeMetaDetails") + protected DeviceTypeMetaDetails deviceTypeMetaDetails; public DeviceTypePlatformDetails getDeviceTypePlatformDetails() { return deviceTypePlatformDetails; @@ -412,4 +415,12 @@ public class DeviceTypeConfiguration { DeviceEnrollmentInvitationDetails deviceEnrollmentInvitationDetails) { this.deviceEnrollmentInvitationDetails = deviceEnrollmentInvitationDetails; } + + public DeviceTypeMetaDetails getDeviceTypeMetaDetails() { + return deviceTypeMetaDetails; + } + + public void setDeviceTypeMetaDetails(DeviceTypeMetaDetails deviceTypeMetaDetails) { + this.deviceTypeMetaDetails = deviceTypeMetaDetails; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java index 37ca202dfa..5a81a5be18 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/java/io/entgra/device/mgt/core/device/mgt/extensions/mock/TypeXDeviceManagementService.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringMa import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; import java.util.ArrayList; @@ -118,4 +119,9 @@ public class TypeXDeviceManagementService implements DeviceManagementService { @Override public License getLicenseConfig() { return null; } + + @Override + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return null; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml index 6cb6789f7f..14eb72c1f4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.url.printer/pom.xml @@ -23,7 +23,7 @@ device-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index d5d99ff127..b3b347666b 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml index 7565c33587..61eb9b42fb 100644 --- a/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.device.mgt.core.server.bootup.heartbeat.beacon/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heartbeat-management - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index 5bf8605825..3cd9312200 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml index 46a8b15955..2dbd213b28 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.device.mgt.oauth.extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml index 0c872c556e..eaed87907f 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core identity-extensions - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java index a2ae303414..2675314524 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/JWTClient.java @@ -138,7 +138,9 @@ public class JWTClient { if (jwtConfig == null) { return null; } - URL tokenEndpoint = new URL(jwtConfig.getTokenEndpoint()); +// todo: +// URL tokenEndpoint = new URL(jwtConfig.getTokenEndpoint()); + URL tokenEndpoint = new URL("https://localhost:9443/oauth2/token"); HttpClient httpClient = JWTClientUtil.getHttpClient(tokenEndpoint.getProtocol()); HttpPost postMethod = new HttpPost(tokenEndpoint.toString()); postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); diff --git a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java index b223a98a66..e2e5d30bb4 100644 --- a/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java +++ b/components/identity-extensions/io.entgra.device.mgt.core.identity.jwt.client.extension/src/main/java/io/entgra/device/mgt/core/identity/jwt/client/extension/util/JWTClientUtil.java @@ -218,8 +218,7 @@ public class JWTClientUtil { long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000; String jti = jwtConfig.getJti(); if (jti == null) { - String defaultTokenId = currentTimeMillis + "" + new SecureRandom().nextInt(); - jti = defaultTokenId; + jti = currentTimeMillis + "" + new SecureRandom().nextInt(); } List aud = jwtConfig.getAudiences(); //set up the basic claims @@ -273,8 +272,7 @@ public class JWTClientUtil { JWSSigner signer = new RSASSASigner(rsaPrivateKey); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet.build()); signedJWT.sign(signer); - String assertion = signedJWT.serialize(); - return assertion; + return signedJWT.serialize(); } catch (KeyStoreException e) { throw new JWTClientException("Failed loading the keystore.", e); } catch (IOException e) { diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index c46e433f55..01c4c03301 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml index 7774776d42..4463270551 100644 --- a/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml +++ b/components/logger/io.entgra.device.mgt.core.notification.logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT io.entgra.device.mgt.core.notification.logger diff --git a/components/logger/pom.xml b/components/logger/pom.xml index 61e4bb82c7..a145b0153b 100644 --- a/components/logger/pom.xml +++ b/components/logger/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml index 2f1e5ed25f..2577775167 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core operation-template-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/operation-template-mgt/pom.xml b/components/operation-template-mgt/pom.xml index 16ed95de0b..0a6afc87a5 100644 --- a/components/operation-template-mgt/pom.xml +++ b/components/operation-template-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml index ed44f640a0..7712408444 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.decision.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml index ce1c3fb600..a5c72ad841 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.information.point/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml index 81151e26cb..99ae59606e 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml index 4e4e734e66..ecd7836c77 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core policy-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TypeXDeviceManagementService.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TypeXDeviceManagementService.java index 6fad650b84..db4f5d7037 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TypeXDeviceManagementService.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/java/io/entgra/device/mgt/core/policy/mgt/core/mock/TypeXDeviceManagementService.java @@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyMonitoringMa import io.entgra.device.mgt.core.device.mgt.common.pull.notification.PullNotificationSubscriber; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.spi.DeviceManagementService; +import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceTypePlatformDetails; import java.util.ArrayList; @@ -118,4 +119,9 @@ public class TypeXDeviceManagementService implements DeviceManagementService { @Override public License getLicenseConfig() { return null; } + + @Override + public DeviceTypeMetaDefinition getDeviceTypeMetaDefinition() { + return null; + } } diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml index 83a54c18c3..a3f393c8a5 100644 --- a/components/policy-mgt/pom.xml +++ b/components/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml index 4941cff12b..93c2025c81 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core subtype-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/subtype-mgt/pom.xml b/components/subtype-mgt/pom.xml index 19bacdf54d..934ff1b4dd 100644 --- a/components/subtype-mgt/pom.xml +++ b/components/subtype-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml index 3fc9ee0375..4c97c8b86f 100755 --- a/components/task-mgt/pom.xml +++ b/components/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml index 2c01f24966..c5cdc94671 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.common/pom.xml @@ -20,7 +20,7 @@ task-manager io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml index ee69355b97..7e93c636b8 100755 --- a/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml +++ b/components/task-mgt/task-manager/io.entgra.device.mgt.core.task.mgt.core/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-manager - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-manager/pom.xml b/components/task-mgt/task-manager/pom.xml index 83a3462056..c6345fccac 100755 --- a/components/task-mgt/task-manager/pom.xml +++ b/components/task-mgt/task-manager/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml index a2ce469206..7341ebfed0 100755 --- a/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml +++ b/components/task-mgt/task-watcher/io.entgra.device.mgt.core.task.mgt.watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-watcher - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/task-mgt/task-watcher/pom.xml b/components/task-mgt/task-watcher/pom.xml index ebc0ec502c..c00b33fd70 100755 --- a/components/task-mgt/task-watcher/pom.xml +++ b/components/task-mgt/task-watcher/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core task-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml index caed6c8c97..94d038c021 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml index 7c78186739..46daa0f40c 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml @@ -20,7 +20,7 @@ tenant-mgt io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/tenant-mgt/pom.xml b/components/tenant-mgt/pom.xml index 3b1cbd62c7..3913c59bbc 100644 --- a/components/tenant-mgt/pom.xml +++ b/components/tenant-mgt/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml index d852a1ef09..1618b2db29 100644 --- a/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml +++ b/components/transport-mgt/email-sender/io.entgra.device.mgt.core.transport.mgt.email.sender.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/email-sender/pom.xml b/components/transport-mgt/email-sender/pom.xml index c57dd3e521..f85d185c75 100644 --- a/components/transport-mgt/email-sender/pom.xml +++ b/components/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/pom.xml b/components/transport-mgt/pom.xml index 00911ea4e6..ef9b6e2f71 100644 --- a/components/transport-mgt/pom.xml +++ b/components/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml index 4e46b89434..a9080a2553 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml index 465f64fe9e..2bf825f05c 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.common/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml index 51e0500a75..1502bab618 100644 --- a/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml +++ b/components/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.core/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/transport-mgt/sms-handler/pom.xml b/components/transport-mgt/sms-handler/pom.xml index abbf64776e..f106779a9b 100644 --- a/components/transport-mgt/sms-handler/pom.xml +++ b/components/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml index f00ed2b1de..747dd9b838 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT 4.0.0 @@ -151,13 +151,10 @@ commons-logging commons-logging - - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 - - org.apache.httpcomponents httpcore @@ -335,10 +332,6 @@ javax.websocket javax.websocket-api - - xerces.wso2 - xercesImpl - org.json.wso2 json diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java index 343a9c620d..b0974a46a5 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultOauth2TokenHandler.java @@ -18,21 +18,20 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import javax.servlet.annotation.MultipartConfig; @@ -42,11 +41,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Map; @MultipartConfig @WebServlet("/default-oauth2-credentials") public class DefaultOauth2TokenHandler extends HttpServlet { private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); + private static final long serialVersionUID = 2254408216447549205L; @Override @@ -80,17 +81,16 @@ public class DefaultOauth2TokenHandler extends HttpServlet { } } - String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR - + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId - + "/" + clientSecret + "/default-token" + scopeString; - - HttpGet defaultTokenRequest = new HttpGet(tokenUrl); - defaultTokenRequest - .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - defaultTokenRequest - .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + ClassicHttpRequest defaultTokenRequest = + ClassicRequestBuilder.get(req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()) + + "/api/device-mgt/v1.0/devices/" + clientId + HandlerConstants.URI_SEPARATOR + + clientSecret + "/default-token" + scopeString) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()) + .build(); + ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { @@ -98,29 +98,24 @@ public class DefaultOauth2TokenHandler extends HttpServlet { HandlerUtil.handleError(resp, tokenResultResponse); return; } - String tokenResult = tokenResultResponse.getData(); + JsonNode tokenResult = tokenResultResponse.getData(); if (tokenResult == null) { log.error("Invalid default token response is received."); HandlerUtil.handleError(resp, tokenResultResponse); return; } - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - AuthData newDefaultAuthData = new AuthData(); - newDefaultAuthData.setClientId(clientId); - newDefaultAuthData.setClientSecret(clientSecret); - - String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); - newDefaultAuthData.setAccessToken(defaultToken); - newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); - newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); - httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); - - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); - } + AuthData newDefaultAuthData = new AuthData(); + newDefaultAuthData.setClientId(clientId); + newDefaultAuthData.setClientSecret(clientSecret); + + String defaultToken = tokenResult.get("accessToken").asText(); + newDefaultAuthData.setAccessToken(defaultToken); + newDefaultAuthData.setRefreshToken(tokenResult.get("refreshToken").asText()); + newDefaultAuthData.setScope(tokenResult.get("scopes").asText()); + httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); + + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); } else { HandlerUtil.sendUnAuthorizeResponse(resp); } @@ -152,19 +147,19 @@ public class DefaultOauth2TokenHandler extends HttpServlet { ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); - JsonObject responseJsonObj = new JsonObject(); - responseJsonObj.addProperty("default-access-token", defaultAccessToken); - responseJsonObj.addProperty("remote-session-base-url", ub.toString()); - responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); - responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); - - Gson gson = new Gson(); - String payload = gson.toJson(responseJsonObj); + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = JsonNodeFactory.instance.objectNode(); + Map nodeMap = mapper.convertValue(node, new TypeReference<>() { + }); + nodeMap.put("default-access-token", defaultAccessToken); + nodeMap.put("remote-session-base-url", ub.toString()); + nodeMap.put("secured-websocket-gateway-url", ub2.toString()); + nodeMap.put("unsecured-websocket-gateway-url", ub3.toString()); ProxyResponse proxyResponse = new ProxyResponse(); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(payload); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); return proxyResponse; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java index e61cafd169..951b7b577a 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/DefaultTokenHandler.java @@ -18,8 +18,10 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.Gson; -import com.google.gson.JsonObject; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; @@ -43,11 +45,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Map; @MultipartConfig @WebServlet("/default-credentials") public class DefaultTokenHandler extends HttpServlet { private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); + private static final long serialVersionUID = 6356346497117534430L; @Override @@ -110,19 +114,19 @@ public class DefaultTokenHandler extends HttpServlet { ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); - JsonObject responseJsonObj = new JsonObject(); - responseJsonObj.addProperty("default-access-token", defaultAccessToken); - responseJsonObj.addProperty("remote-session-base-url", ub.toString()); - responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); - responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); - - Gson gson = new Gson(); - String payload = gson.toJson(responseJsonObj); + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = JsonNodeFactory.instance.objectNode(); + Map nodeMap = mapper.convertValue(node, new TypeReference<>() { + }); + nodeMap.put("default-access-token", defaultAccessToken); + nodeMap.put("remote-session-base-url", ub.toString()); + nodeMap.put("secured-websocket-gateway-url", ub2.toString()); + nodeMap.put("unsecured-websocket-gateway-url", ub3.toString()); ProxyResponse proxyResponse = new ProxyResponse(); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(payload); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); return proxyResponse; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java index 5fc86acde2..414067ff20 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/GrafanaHandler.java @@ -30,12 +30,12 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.*; -import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -68,7 +68,7 @@ public class GrafanaHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet grafanaRequest = new HttpGet(); + ClassicHttpRequest grafanaRequest = ClassicRequestBuilder.get().build(); HandlerUtil.copyRequestHeaders(req, grafanaRequest, true); if (!GrafanaUtil.isGrafanaAPI(req.getRequestURI())) { proxyPassGrafanaRequest(grafanaRequest, resp, req); @@ -112,7 +112,7 @@ public class GrafanaHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost grafanaRequest = new HttpPost(); + ClassicHttpRequest grafanaRequest = ClassicRequestBuilder.post().build(); HandlerUtil.generateRequestEntity(req, grafanaRequest); HandlerUtil.copyRequestHeaders(req, grafanaRequest, true); if (!GrafanaUtil.isGrafanaAPI(req.getRequestURI())) { @@ -206,10 +206,10 @@ public class GrafanaHandler extends HttpServlet { return true; } - private ProxyResponse executeGrafanaAPIRequest(HttpRequestBase requestBase, HttpServletRequest request) + private ProxyResponse executeGrafanaAPIRequest(ClassicHttpRequest requestBase, HttpServletRequest request) throws IOException { URI grafanaUri = HttpUtil.createURI(generateGrafanaAPIUrl(request)); - requestBase.setURI(grafanaUri); + requestBase.setUri(grafanaUri); return HandlerUtil.execute(requestBase); } @@ -230,14 +230,14 @@ public class GrafanaHandler extends HttpServlet { } return uri; } - private void proxyPassGrafanaRequest(HttpRequestBase requestBase, HttpServletResponse response, + private void proxyPassGrafanaRequest(ClassicHttpRequest requestBase, HttpServletResponse response, HttpServletRequest request) throws IOException { try (CloseableHttpClient client = HandlerUtil.getHttpClient()) { String grafanaUriStr = GrafanaHandlerUtil.generateGrafanaUrl(HttpUtil.createURI(getURIWithQuery(request)), GrafanaUtil.getGrafanaHTTPBase(request.getScheme())); URI grafanaURI = HttpUtil.createURI(grafanaUriStr); - requestBase.setURI(grafanaURI); - HttpResponse grafanaResponse = invokeGrafanaAPI(client, requestBase); + requestBase.setUri(grafanaURI); + CloseableHttpResponse grafanaResponse = invokeGrafanaAPI(client, requestBase); forwardGrafanaResponse(grafanaResponse, response); } catch (GrafanaEnvVariablesNotDefined e) { handleError(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); @@ -248,17 +248,19 @@ public class GrafanaHandler extends HttpServlet { } } - private HttpResponse invokeGrafanaAPI(HttpClient client, HttpRequestBase request) throws IOException, GrafanaManagementException { + private CloseableHttpResponse invokeGrafanaAPI(CloseableHttpClient client, ClassicHttpRequest request) throws IOException, + GrafanaManagementException { setBasicAuthHeader(request); + //todo this is deprecated call return client.execute(request); } - private void setBasicAuthHeader(HttpRequestBase request) throws GrafanaManagementException { + private void setBasicAuthHeader(ClassicHttpRequest request) throws GrafanaManagementException { String basicAuth = GrafanaUtil.getBasicAuthBase64Header(); request.setHeader(HttpHeaders.AUTHORIZATION, basicAuth); } - private void forwardGrafanaResponse(HttpResponse grafanaResponse, HttpServletResponse response) throws IOException { + private void forwardGrafanaResponse(CloseableHttpResponse grafanaResponse, HttpServletResponse response) throws IOException { InputStream responseContent = grafanaResponse.getEntity().getContent(); String grafanaContentType = HandlerUtil.getMemeType(grafanaResponse); response.setHeader(HttpHeaders.CONTENT_TYPE, grafanaContentType); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java index 2e2f5b73bf..f99531cc17 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/HubspotHandler.java @@ -18,17 +18,15 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonObject; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import com.fasterxml.jackson.databind.JsonNode; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -48,89 +46,94 @@ import java.io.IOException; ) public class HubspotHandler extends HttpServlet { - private static final Log log = LogFactory.getLog(HubspotHandler.class); - private HttpSession httpSession; - private static String hubspotEndpoint; - private static String chatConfig; - private JsonObject uiConfigJsonObject; - private static String gatewayUrl; - private static String iotsCoreUrl; + private static final Log log = LogFactory.getLog(HubspotHandler.class); + private HttpSession httpSession; + private static String hubspotEndpoint; + private static String chatConfig; + private JsonNode uiConfigJsonObject; + private static String gatewayUrl; + private static String iotsCoreUrl; - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) { - try { - if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)); - HandlerUtil.generateChatRequestEntity(req, postRequest); - postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e) { - log.error("Error occurred when processing POST request.", e); - } + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig) + .build(); + HandlerUtil.generateChatRequestEntity(req, postRequest); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(postRequest)); + } + } catch (IOException e) { + log.error("Error occurred when processing POST request.", e); } + } - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) { - try { - if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); - getRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e) { - log.error("Error occurred when processing GET request.", e); - } + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest getRequest = + ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, + HandlerConstants.BEARER + chatConfig).build(); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(getRequest)); + } + } catch (IOException e) { + log.error("Error occurred when processing GET request.", e); } + } + + @Override + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { + try { + if (validateRequest(req, resp)) { + ClassicHttpRequest deleteRequest = + ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json") + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, + HandlerConstants.BEARER + chatConfig).build(); - @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp){ - try{ - if(validateRequest(req, resp)){ - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); - deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); - ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); - HandlerUtil.handleSuccess(resp, proxyResponse); - } - } catch (IOException e){ - log.error("Error occurred when processing DELETE request.", e); + deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); + deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); + HandlerUtil.handleSuccess(resp, HandlerUtil.execute(deleteRequest)); } + } catch (IOException e) { + log.error("Error occurred when processing DELETE request.", e); } + } - /*** - * Validates the hubspot's incoming request. - * - * @param req {@link HttpServletRequest} - * @param resp {@link HttpServletResponse} - * @return If request is a valid one, returns TRUE, otherwise return FALSE - * @throws IOException If and error occurs while witting error response to client side - */ - private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - httpSession = req.getSession(false); - if (httpSession == null) { - log.error("Unauthorized, You are not logged in. Please log in to the portal"); - HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); - return false; - } - if (req.getMethod() == null) { - log.error("Bad Request, Request method is empty"); - HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST); - return false; - } - 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(HandlerConstants.IOT_CORE_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); - String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; - uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - chatConfig = uiConfigJsonObject.get("hubspotChat").getAsJsonObject().get("accessToken").getAsString(); - hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; - return true; + /*** + * Validates the hubspot's incoming request. + * + * @param req {@link HttpServletRequest} + * @param resp {@link HttpServletResponse} + * @return If request is a valid one, returns TRUE, otherwise return FALSE + * @throws IOException If and error occurs while witting error response to client side + */ + private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + httpSession = req.getSession(false); + if (httpSession == null) { + log.error("Unauthorized, You are not logged in. Please log in to the portal"); + HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); + return false; + } + if (req.getMethod() == null) { + log.error("Bad Request, Request method is empty"); + HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST); + return false; } + 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(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); + String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); + chatConfig = uiConfigJsonObject.get("hubspotChat").get("accessToken").textValue(); + hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; + return true; + } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java index ed6d636afd..e8ffb2deef 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/InvokerHandler.java @@ -26,9 +26,10 @@ import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.*; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -58,7 +59,7 @@ public class InvokerHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, postRequest); postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); @@ -88,7 +89,8 @@ public class InvokerHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest getRequest = ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, getRequest, false); getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); @@ -123,7 +125,8 @@ public class InvokerHandler extends HttpServlet { protected void doHead(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpHead headRequest = new HttpHead(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest headRequest = ClassicRequestBuilder.head(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, headRequest, false); headRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(headRequest); @@ -150,7 +153,8 @@ public class InvokerHandler extends HttpServlet { protected void doPut(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPut putRequest = new HttpPut(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest putRequest = ClassicRequestBuilder.put(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, putRequest); putRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(putRequest); @@ -180,7 +184,8 @@ public class InvokerHandler extends HttpServlet { protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest deleteRequest = ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req, + apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, deleteRequest, false); deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java index b058322933..6f38a18014 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/LoginHandler.java @@ -18,6 +18,8 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.gson.*; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; @@ -29,12 +31,12 @@ import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.protocol.HTTP; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; +import org.apache.hc.core5.http.message.BasicNameValuePair; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -43,7 +45,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; -import java.util.Base64; +import java.util.*; @MultipartConfig @WebServlet("/login") @@ -68,9 +70,10 @@ public class LoginHandler extends HttpServlet { } httpSession = req.getSession(true); - JsonObject uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); - JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + JsonNode uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, + resp); + ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags"); + ArrayNode scopes = (ArrayNode) uiConfigJsonObject.get("scopes"); int sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); //setting session to expire in 1h @@ -82,11 +85,14 @@ public class LoginHandler extends HttpServlet { OAuthApp oAuthApp = loginCache.getOAuthAppCache(oAuthAppCacheKey); 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)); + + ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT) + .setEntity(HandlerUtil.constructAppRegPayload(tags, HandlerConstants.PUBLISHER_APPLICATION_NAME, + username, password, null, null)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((username + HandlerConstants.COLON + password).getBytes())) + .build(); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); @@ -96,15 +102,13 @@ public class LoginHandler extends HttpServlet { } if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { - JsonParser jsonParser = new JsonParser(); - JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); + JsonNode jsonNode = 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(); + if (jsonNode != null) { + clientId = jsonNode.get("client_id").textValue(); + clientSecret = jsonNode.get("client_secret").textValue(); encodedClientApp = Base64.getEncoder() .encodeToString((clientId + HandlerConstants.COLON + clientSecret).getBytes()); oAuthApp = new OAuthApp( @@ -152,8 +156,7 @@ public class LoginHandler extends HttpServlet { */ private boolean getTokenAndPersistInSession(HttpServletRequest req, HttpServletResponse resp, String clientId, String clientSecret, String encodedClientApp, - JsonArray scopes) throws LoginException { - JsonParser jsonParser = new JsonParser(); + ArrayNode scopes) throws LoginException { try { ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp, scopes); @@ -163,31 +166,26 @@ public class LoginHandler extends HttpServlet { HandlerUtil.handleError(resp, tokenResultResponse); return false; } - String tokenResult = tokenResultResponse.getData(); + JsonNode 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; + HttpSession session = req.getSession(false); + if (session == null) { + return false; } - return false; + AuthData authData = new AuthData(); + authData.setClientId(clientId); + authData.setClientSecret(clientSecret); + authData.setEncodedClientApp(encodedClientApp); + authData.setAccessToken(tokenResult.get("access_token").textValue()); + authData.setRefreshToken(tokenResult.get("refresh_token").textValue()); + authData.setScope(tokenResult.get("scope").textValue()); + session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); + return true; } catch (IOException e) { throw new LoginException("Error occurred while sending the response into the socket", e); } @@ -224,23 +222,27 @@ public class LoginHandler extends HttpServlet { * @return Invoke token endpoint and return the response as string. * @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.INTERNAL_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + private ProxyResponse getTokenResult(String encodedClientApp, JsonNode scopes) throws IOException { String scopeString = HandlerUtil.getScopeString(scopes); - if (scopeString != null) { scopeString = scopeString.trim(); } else { scopeString = "default"; } - StringEntity tokenEPPayload = new StringEntity( - "grant_type=" + HandlerConstants.PASSWORD_GRANT_TYPE + "&username=" + username + "&password=" + - password + "&scope=" + scopeString, - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair("grant_type", HandlerConstants.PASSWORD_GRANT_TYPE)); + nameValuePairs.add(new BasicNameValuePair("username", username)); + nameValuePairs.add(new BasicNameValuePair("password", password)); + nameValuePairs.add(new BasicNameValuePair("scope", scopeString)); + + + ClassicHttpRequest tokenEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.INTERNAL_TOKEN_ENDPOINT) + .setEntity(new UrlEncodedFormEntity(nameValuePairs)) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp) + .build(); return HandlerUtil.execute(tokenEndpoint); } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java index 31d851ec03..9e6954fe47 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/OTPInvokerHandler.java @@ -25,8 +25,9 @@ import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.*; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -51,7 +52,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, postRequest); ProxyResponse proxyResponse = HandlerUtil.execute(postRequest); @@ -73,7 +75,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest getRequest = ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, getRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); @@ -93,7 +96,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doHead(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpHead headRequest = new HttpHead(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest headRequest = ClassicRequestBuilder.head(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, headRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(headRequest); @@ -113,7 +117,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doPut(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpPut putRequest = new HttpPut(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest putRequest = ClassicRequestBuilder.put(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.generateRequestEntity(req, putRequest); ProxyResponse proxyResponse = HandlerUtil.execute(putRequest); @@ -135,7 +140,8 @@ public class OTPInvokerHandler extends HttpServlet { protected void doDelete(HttpServletRequest req, HttpServletResponse resp) { try { if (validateRequest(req, resp)) { - HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req, apiEndpoint)); + ClassicHttpRequest deleteRequest = ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req + , apiEndpoint)).build(); HandlerUtil.copyRequestHeaders(req, deleteRequest, false); ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java index 80b88885b7..623fd48b87 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/PermissionScopeHandler.java @@ -18,15 +18,17 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.lang.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; @@ -34,12 +36,15 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.Map; @MultipartConfig @WebServlet("/login-user/scopes") public class PermissionScopeHandler extends HttpServlet { + private static final long serialVersionUID = 976006906915355611L; + @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { HttpSession httpSession = req.getSession(false); if (httpSession == null) { HandlerUtil.sendUnAuthorizeResponse(resp); @@ -54,11 +59,15 @@ public class PermissionScopeHandler extends HttpServlet { if (!StringUtils.isEmpty(authData.getScope())) { ProxyResponse proxyResponse = new ProxyResponse(); - JSONObject jsonObject = new JSONObject(); - jsonObject.put(HandlerConstants.USER_SCOPES, authData.getScope()); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = JsonNodeFactory.instance.objectNode(); + Map nodeMap = mapper.convertValue(node, new TypeReference<>() { + }); + nodeMap.put(HandlerConstants.USER_SCOPES, authData.getScope()); proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setData(jsonObject.toString()); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); HandlerUtil.handleSuccess(resp, proxyResponse); return; } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java index 242ce38962..ee2b600eb4 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginCallbackHandler.java @@ -18,20 +18,18 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -75,33 +73,35 @@ public class SsoLoginCallbackHandler extends HttpServlet { } String scope = session.getAttribute("scope").toString(); - - HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp")); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - String loginCallbackUrl = iotsCoreUrl + req.getContextPath() + HandlerConstants.SSO_LOGIN_CALLBACK; StringEntity tokenEPPayload = new StringEntity( "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + "&redirect_uri=" + loginCallbackUrl, ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); + + ClassicHttpRequest tokenEndpoint = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT) + .setEntity(tokenEPPayload) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp")) + .build(); + ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); + JsonNode jsonNode = tokenResultResponse.getData(); - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); + if (jsonNode != null) { AuthData authData = new AuthData(); authData.setClientId(session.getAttribute("clientId").toString()); authData.setClientSecret(session.getAttribute("clientSecret").toString()); authData.setEncodedClientApp(session.getAttribute("encodedClientApp").toString()); - authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); + authData.setAccessToken(jsonNode.get("access_token").textValue()); + authData.setRefreshToken(jsonNode.get("refresh_token").textValue()); + authData.setScope(jsonNode.get("scope").textValue()); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); resp.sendRedirect(session.getAttribute("redirectUrl").toString()); + } else { + log.error("Found empty response for token call."); + HandlerUtil.handleError(resp, HandlerConstants.INTERNAL_ERROR_CODE); } } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java index ca469ca7e6..34584d03c3 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java @@ -18,29 +18,21 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.*; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthAppCacheKey; +import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.LoginException; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.lang.text.StrSubstitutor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONObject; import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.servlet.annotation.MultipartConfig; @@ -54,30 +46,25 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; -import java.io.StringReader; +import java.util.ArrayList; import java.util.Base64; -import java.util.HashMap; -import java.util.Map; @MultipartConfig @WebServlet("/ssoLogin") public class SsoLoginHandler extends HttpServlet { private static final Log log = LogFactory.getLog(SsoLoginHandler.class); + private static final long serialVersionUID = 5594017767311123453L; private static String adminUsername; private static String adminPassword; private static String gatewayUrl; - private static String iotsCoreUrl; - private static String apiMgtUrl; - private static String keyManagerUrl; + 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 JsonNode uiConfigJsonObject; private HttpSession httpSession; private LoginCache loginCache; private OAuthApp oAuthApp; @@ -101,15 +88,14 @@ public class SsoLoginHandler extends HttpServlet { 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(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + iotSCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); - apiMgtUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_APIM_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getAPIManagerPort(req.getScheme()); - keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + String keyManagerUrl = + req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); // Fetch ui config and persists in session - String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + String uiConfigUrl = iotSCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); // Retrieving login cache and do a DCR if the cache is not available. @@ -121,9 +107,10 @@ public class SsoLoginHandler extends HttpServlet { } String clientId = oAuthApp.getClientId(); - JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray(); - String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); - String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; + + JsonNode scopeJsonNode = uiConfigJsonObject.get("scopes"); + String scopesSsoString = HandlerUtil.getScopeString(scopeJsonNode); + String loginCallbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), oAuthApp.getEncodedClientApp(), scopesSsoString, state); resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + @@ -134,12 +121,12 @@ public class SsoLoginHandler extends HttpServlet { "&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); + } catch (LoginException e) { + log.error("SSO Login is failed. Application: " + applicationName, e); } } @@ -150,37 +137,34 @@ public class SsoLoginHandler extends HttpServlet { * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ - private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) { + private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException { try { - JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); - JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); + ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags"); + JsonNode scopes = uiConfigJsonObject.get("scopes"); sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); + String callbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; - // Register the client application - HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - encodedAdminCredentials = Base64.getEncoder() + String encodedAdminCredentials = Base64.getEncoder() .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()); - apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword)); + ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT) + .setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword, + callbackUrl, constructAppGrantTypeUpdateArray())) + .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, + org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString()) + .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + + encodedAdminCredentials) + .build(); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); - if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, clientAppResponse); - } - if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { - JsonParser jsonParser = new JsonParser(); - JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); String clientId = null; String clientSecret = null; + JsonNode jsonNode = clientAppResponse.getData(); - if (jClientAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); - clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); - clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString(); + if (jsonNode != null) { + clientId = jsonNode.get("client_id").textValue(); + clientSecret = jsonNode.get("client_secret").textValue(); encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()); String scopesString = HandlerUtil.getScopeString(scopes); persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state); @@ -189,70 +173,22 @@ public class SsoLoginHandler extends HttpServlet { // cache the oauth app credentials oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp); loginCache.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); + } else if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { + String msg = "Unauthorized attempt to register the client application. " + + "Application Name: " + applicationName + ". Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, clientAppResponse); + throw new LoginException(msg); + } else { + String msg = "Failed the process while registering the client application. " + + "Application Name: " + applicationName + ". Response Code: " + + clientAppResponse.getCode() + ", Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, null); + throw new LoginException(msg); } - - // Get the details of the registered application - String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + - "?query=" + applicationName; - HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl); - getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - - ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint); - - if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, getApplicationResponse); - return; - } - - if (getApplicationResponse.getCode() == HttpStatus.SC_OK) { - JsonParser jsonParser = new JsonParser(); - JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData()); - if (jAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject(); - JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list"); - JsonObject app; - for (JsonElement appJson : appList) { - app = appJson.getAsJsonObject(); - if (app.get("name").getAsString().equals(applicationName)) { - applicationId = app.get("applicationId").getAsString(); - break; - } - } - } - } - - // Update the grant types of the application - String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + applicationId + "/keys/" + - HandlerConstants.PRODUCTION_KEY; - HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload()); - - ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); - - // Update app as a SaaS app - this.updateSaasApp(applicationId); - - if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); - return; - } - - 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); - } 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); + throw new LoginException("Error occurred while sending the response into the socket.", e); } } @@ -273,7 +209,6 @@ public class SsoLoginHandler extends HttpServlet { adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent(); } - /** * Persist the Auth data inside the session * @@ -298,172 +233,14 @@ public class SsoLoginHandler extends HttpServlet { /*** * Generates payload for application grant_type update payload * - * @return {@link StringEntity} of the payload to update application grant type + * @return {@link ArrayList} of the payload to update application grant type */ - private StringEntity constructAppGrantTypeUpdatePayload() { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("supportedGrantTypes", - new JSONArray(new Object[]{ - HandlerConstants.CODE_GRANT_TYPE, - HandlerConstants.REFRESH_TOKEN_GRANT_TYPE, - HandlerConstants.PASSWORD_GRANT_TYPE, - HandlerConstants.JWT_BEARER_GRANT_TYPE - }) - ); - jsonObject.put(HandlerConstants.CALLBACK_URL_KEY, iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK); - String payload = jsonObject.toString(); - return new StringEntity(payload, ContentType.APPLICATION_JSON); - } - - /*** - * Generates tokens using password grant_type by invoking token endpoint - * - * @param encodedClientApp - Base64 encoded clientId:clientSecret. - * @return Invoke token endpoint and return the response as string. - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - */ - private ProxyResponse getTokenResult(String encodedClientApp) throws IOException { - HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); - tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); - tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - - StringEntity tokenEPPayload = new StringEntity( - "grant_type=" + HandlerConstants.PASSWORD_GRANT_TYPE + "&username=" + adminUsername + "&password=" + adminPassword + - "&scope=apim:api_view apim:api_create apim:api_publish apim:subscribe", - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); - return HandlerUtil.execute(tokenEndpoint); - } - - /*** - * Retrieves and returns access token - * - * @param resp - Http Servlet Response - * @param encodedClientApp - Base64 encoded clientId:clientSecret. - * @return Returns access token - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - */ - private String getAccessToken(HttpServletResponse resp, String encodedClientApp) throws IOException { - ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp); - - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get token data."); - HandlerUtil.handleError(resp, tokenResultResponse); - } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - return jTokenResultAsJsonObject.get("access_token").getAsString(); - } - - /*** - * Updates Application - * - * @param appName - Application name - * @throws IOException IO exception throws if an error occurred when invoking token endpoint - * @throws ParserConfigurationException,SAXException throws if an error occurred when parsing xml - */ - private void updateSaasApp(String appName) throws ParserConfigurationException, IOException, SAXException { - File getAppRequestXmlFile = new File(HandlerConstants.PAYLOADS_DIR + "/get-app-request.xml"); - String identityAppMgtUrl = apiMgtUrl + HandlerConstants.IDENTITY_APP_MGT_ENDPOINT; - - HttpPost getApplicationEndpoint = new HttpPost(identityAppMgtUrl); - getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - getApplicationEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_XML.toString()); - getApplicationEndpoint.setHeader(HandlerConstants.SOAP_ACTION_HEADER, "urn:getApplication"); - - String requestBodyString = HandlerUtil.xmlToString(getAppRequestXmlFile); - - Map data = new HashMap<>(); - appName = adminUsername + HandlerConstants.UNDERSCORE + appName + HandlerConstants.UNDERSCORE + - HandlerConstants.PRODUCTION_KEY; - data.put("applicationName", appName); - requestBodyString = StrSubstitutor.replace(requestBodyString, data); - getApplicationEndpoint.setEntity(new StringEntity(requestBodyString, ContentType.TEXT_XML)); - - ProxyResponse getApplicationEndpointResponse = HandlerUtil.execute(getApplicationEndpoint); - - Document doc = DocumentBuilderFactory.newInstance() - .newDocumentBuilder() - .parse(new InputSource(new StringReader(getApplicationEndpointResponse.getData()))); - NodeList nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "inboundAuthenticationConfig"); - NodeList childNodeList; - String nodeName; - - data.clear(); - data.put("applicationId", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "applicationID").item(0).getTextContent()); - data.put("applicationName", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "applicationName").item(0).getTextContent()); - data.put("description", doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "description").item(0).getTextContent()); - data.put("saasApp", "true"); - - for (int i = 0; i < nodeList.getLength(); i++) { - childNodeList = nodeList.item(i).getChildNodes(); - for (int j = 0; j < childNodeList.getLength(); j++) { - if (childNodeList.item(j).getNodeName().equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthenticationRequestConfigs")) { - NodeList inboundAuthRequestConfigs = childNodeList.item(j).getChildNodes(); - for (int k = 0; k < inboundAuthRequestConfigs.getLength(); k++) { - nodeName = inboundAuthRequestConfigs.item(k).getNodeName(); - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthKey")) { - data.put("inboundAuthKey", inboundAuthRequestConfigs.item(k).getTextContent()); - } - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundAuthType")) { - data.put("inboundAuthType", inboundAuthRequestConfigs.item(k).getTextContent()); - } - if (nodeName.equalsIgnoreCase(HandlerConstants.AX_PREFIX + "inboundConfigType")) { - data.put("inboundConfigType", inboundAuthRequestConfigs.item(k).getTextContent()); - } - } - } - } - } - - nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "owner"); - for (int i = 0; i < nodeList.getLength(); i++) { - childNodeList = nodeList.item(i).getChildNodes(); - for (int j = 0; j < childNodeList.getLength(); j++) { - switch (childNodeList.item(j).getNodeName()) { - case HandlerConstants.AX_PREFIX + "tenantDomain": - data.put("tenantDomain", childNodeList.item(j).getTextContent()); - break; - case HandlerConstants.AX_PREFIX + "userName": - data.put("userName", childNodeList.item(j).getTextContent()); - break; - case HandlerConstants.AX_PREFIX + "userStoreDomain": - data.put("userStoreDomain", childNodeList.item(j).getTextContent()); - break; - } - } - } - - nodeList = doc.getElementsByTagName(HandlerConstants.AX_PREFIX + "spProperties"); - for (int k = 0; k < nodeList.getLength(); k++) { - childNodeList = nodeList.item(k).getChildNodes(); - for (int l = 0; l < childNodeList.getLength(); l++) { - if (childNodeList.item(l).getNodeName().equalsIgnoreCase(HandlerConstants.AX_PREFIX + "value")) { - data.put("displayName", childNodeList.item(l).getTextContent()); - } - } - } - - File appUpdateRequest = new File(HandlerConstants.PAYLOADS_DIR + "/update-app-request.xml"); - String docStr = HandlerUtil.xmlToString(appUpdateRequest); - requestBodyString = StrSubstitutor.replace(docStr, data); - - HttpPost updateApplicationEndpoint = new HttpPost(identityAppMgtUrl); - updateApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + - encodedAdminCredentials); - updateApplicationEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_XML.toString()); - updateApplicationEndpoint.setHeader(HandlerConstants.SOAP_ACTION_HEADER, "urn:updateApplication"); - updateApplicationEndpoint.setEntity(new StringEntity(requestBodyString, ContentType.TEXT_XML)); - - HandlerUtil.execute(updateApplicationEndpoint); + private ArrayList constructAppGrantTypeUpdateArray() { + ArrayList jsonArray = new ArrayList<>(); + jsonArray.add(HandlerConstants.CODE_GRANT_TYPE); + jsonArray.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE); + jsonArray.add(HandlerConstants.PASSWORD_GRANT_TYPE); + jsonArray.add(HandlerConstants.JWT_BEARER_GRANT_TYPE); + return jsonArray; } } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java index c0f6c7f6ee..dd06e5f08c 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java @@ -18,9 +18,9 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonSyntaxException; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; @@ -31,11 +31,14 @@ import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.core5.http.ClassicHttpRequest; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; +import org.apache.hc.core5.http.message.BasicNameValuePair; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -44,7 +47,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; +import java.util.ArrayList; import java.util.Base64; +import java.util.List; +import java.util.Map; @MultipartConfig @WebServlet("/user") @@ -56,7 +62,7 @@ public class UserHandler extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { try { - String keymanagerUrl = + String keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); @@ -73,24 +79,24 @@ public class UserHandler extends HttpServlet { } String accessToken = authData.getAccessToken(); - String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); - - HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + 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=" + accessTokenWithoutPrefix, - ContentType.APPLICATION_FORM_URLENCODED); - tokenEndpoint.setEntity(tokenEPPayload); - ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair("token", accessToken)); + + ClassicHttpRequest introspectCall = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.INTROSPECT_ENDPOINT) + .setEntity(new UrlEncodedFormEntity(nameValuePairs)) + .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()) + .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())) + .build(); + + ProxyResponse tokenStatus = HandlerUtil.execute(introspectCall); if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) { - tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, keymanagerUrl); - if(!HandlerUtil.isResponseSuccessful(tokenStatus)) { + tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, introspectCall, keyManagerUrl); + if (!HandlerUtil.isResponseSuccessful(tokenStatus)) { HandlerUtil.handleError(resp, tokenStatus); return; } @@ -100,29 +106,31 @@ public class UserHandler extends HttpServlet { return; } } - String tokenData = tokenStatus.getData(); + JsonNode tokenData = tokenStatus.getData(); if (tokenData == null) { log.error("Invalid token data is received."); HandlerUtil.handleError(resp, tokenStatus); return; } - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenData); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) { - HandlerUtil.sendUnAuthorizeResponse(resp); - return; - } - ProxyResponse proxyResponse = new ProxyResponse(); - proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setCode(HttpStatus.SC_OK); - proxyResponse.setData( - jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", "")); - HandlerUtil.handleSuccess(resp, proxyResponse); - httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString()); - log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build()); + + if (!tokenData.get("active").asBoolean()) { + HandlerUtil.sendUnAuthorizeResponse(resp); + return; } + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); + proxyResponse.setCode(HttpStatus.SC_OK); + + ObjectMapper mapper = new ObjectMapper(); + Map nodeMap = mapper.convertValue(tokenData, new TypeReference<>() { + }); + nodeMap.put("username", tokenData.get("username").textValue().replaceAll("@carbon.super", "")); + proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); + + HandlerUtil.handleSuccess(resp, proxyResponse); + httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, nodeMap.get("username").toString()); + log.info("Customer login", + userLogContextBuilder.setUserName(nodeMap.get("username").toString()).setUserRegistered(true).build()); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); } catch (JsonSyntaxException e) { diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java index 263a98bfeb..d259b33314 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ProxyResponse.java @@ -17,7 +17,8 @@ */ package io.entgra.device.mgt.core.ui.request.interceptor.beans; -import org.apache.http.Header; +import com.fasterxml.jackson.databind.JsonNode; +import org.apache.hc.core5.http.Header; public class ProxyResponse { @@ -27,7 +28,7 @@ public class ProxyResponse { } private int code; - private String data; + private JsonNode data; private String executorResponse; private int status; private Header[] headers; @@ -36,9 +37,9 @@ public class ProxyResponse { public void setCode(int code) { this.code = code; } - public String getData() { return data; } + public JsonNode getData() { return data; } - public void setData(String data) { this.data = data; } + public void setData(JsonNode data) { this.data = data; } public String getExecutorResponse() { return executorResponse; } diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java index 9aa9cb9fe6..0b56bbc578 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerConstants.java @@ -26,7 +26,7 @@ public class HandlerConstants { public static final String INTERNAL_TOKEN_ENDPOINT = "/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/devportal/v2/applications/"; + public static final String APIM_APPLICATIONS_ENDPOINT = "/api/am/devportal/v3/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"; @@ -43,6 +43,7 @@ public class HandlerConstants { public static final String SESSION_DEFAULT_AUTH_DATA_KEY = "defaultAuthInfo"; public static final String UI_CONFIG_KEY = "ui-config"; public static final String CALLBACK_URL_KEY = "callbackUrl"; + public static final String GRANT_TYPE_KEY = "supportedGrantTypes"; public static final String IS_ALLOWED_TO_ALL_DOMAINS_KEY = "isAllowedToAllDomains"; public static final String JSESSIONID_KEY = "JSESSIONID"; public static final String COMMON_AUTH_ID_KEY = "commonAuthId"; @@ -77,7 +78,7 @@ public class HandlerConstants { public static final String OTP_HEADER = "one-time-token"; - public static final String AX_PREFIX = "ax2251:"; + public static final String AX_PREFIX = "ax2245:"; public static final String PAYLOADS_DIR = "repository/resources/payloads"; public static final String SOAP_ACTION_HEADER = "SOAPAction"; public static final String REFERER_HEADER = "Referer"; diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java index 0fca3811c0..b7a4b4e51c 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/util/HandlerUtil.java @@ -18,6 +18,10 @@ package io.entgra.device.mgt.core.ui.request.interceptor.util; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -32,49 +36,40 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.*; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.entity.mime.InputStreamBody; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder; +import org.apache.hc.client5.http.ssl.TrustAllStrategy; +import org.apache.hc.core5.http.*; +import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; +import org.apache.hc.core5.http.io.entity.InputStreamEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; +import org.apache.http.Consts; import org.apache.http.cookie.SM; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.InputStreamEntity; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.InputStreamBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.xml.serialize.OutputFormat; -import org.apache.xml.serialize.XMLSerializer; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.w3c.dom.Document; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; -import org.xml.sax.SAXException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.BufferedReader; -import java.io.File; import java.io.IOException; -import java.io.InputStreamReader; +import java.io.InputStream; import java.io.PrintWriter; -import java.io.StringWriter; import java.math.BigInteger; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import java.util.Enumeration; -import java.util.List; +import java.util.*; public class HandlerUtil { @@ -91,71 +86,75 @@ public class HandlerUtil { * @return response as string * @throws IOException IO exception returns if error occurs when executing the httpMethod */ - public static ProxyResponse execute(HttpRequestBase httpRequest) throws IOException { + public static ProxyResponse execute(ClassicHttpRequest httpRequest) throws IOException { + try (CloseableHttpClient client = getHttpClient()) { - HttpResponse response = client.execute(httpRequest); - ProxyResponse proxyResponse = new ProxyResponse(); - - if (response == null) { - log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest - .getURI().toString()); - proxyResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( - HandlerConstants.INTERNAL_ERROR_CODE)); - return proxyResponse; - } else { - int statusCode = response.getStatusLine().getStatusCode(); - String jsonString = getResponseString(response); - if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); - proxyResponse.setExecutorResponse("SUCCESS"); - proxyResponse.setHeaders(response.getAllHeaders()); - return proxyResponse; - } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { - if (isTokenExpired(jsonString)) { - proxyResponse.setCode(statusCode); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); - } else { - log.error( - "Received " + statusCode + " response for http request : " + httpRequest.getMethod() - + " " + httpRequest.getURI().toString() + ". Error message: " + jsonString); - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse.setExecutorResponse( - HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + + JsonFactory jsonFactory = new JsonFactory(); + ObjectMapper objectMapper = new ObjectMapper(jsonFactory); + + return client.execute(httpRequest, response -> { + final HttpEntity responseEntity = response.getEntity(); + ProxyResponse handlerResponse = new ProxyResponse(); + int statusCode = response.getCode(); + if (responseEntity == null) { + log.error("Received null response for http request : " + httpRequest.getMethod() + " " + httpRequest.getRequestUri()); + handlerResponse.setCode(HandlerConstants.INTERNAL_ERROR_CODE); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey( + HandlerConstants.INTERNAL_ERROR_CODE)); + return handlerResponse; + } + try (InputStream inputStream = responseEntity.getContent()) { + JsonNode responseData = objectMapper.readTree(inputStream); + if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.SUCCESS); + handlerResponse.setExecutorResponse("SUCCESS"); + handlerResponse.setHeaders(response.getHeaders()); + return handlerResponse; + } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { + if (isTokenExpired(responseData)) { + handlerResponse.setCode(statusCode); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse(HandlerConstants.TOKEN_IS_EXPIRED); + } else { + log.error( + "Received " + statusCode + " response for http request : " + httpRequest.getMethod() + + " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue()); + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse.setExecutorResponse( + HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + } + return handlerResponse; } - return proxyResponse; + log.error("Received " + statusCode + " response for http request : " + httpRequest.getMethod() + + " " + httpRequest.getRequestUri() + ". Error message: " + responseData.textValue()); + handlerResponse.setCode(statusCode); + handlerResponse.setData(responseData); + handlerResponse.setStatus(ProxyResponse.Status.ERROR); + handlerResponse + .setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); + return handlerResponse; } - log.error("Received " + statusCode + - " response for http request : " + httpRequest.getMethod() + " " + httpRequest.getURI() - .toString() + ". Error message: " + jsonString); - proxyResponse.setCode(statusCode); - proxyResponse.setData(jsonString); - proxyResponse.setStatus(ProxyResponse.Status.ERROR); - proxyResponse - .setExecutorResponse(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + getStatusKey(statusCode)); - return proxyResponse; - } + }); } } - public static boolean isTokenExpired(String jsonBody) { - return jsonBody.contains("Access token expired") || jsonBody + public static boolean isTokenExpired(JsonNode jsonBody) { + return jsonBody.textValue().contains("Access token expired") || jsonBody.textValue() .contains("Invalid input. Access token validation failed"); } public static String getMemeType(HttpResponse response) { - String memeType = ""; - Header contentType = response.getEntity().getContentType(); + Header contentType = response.getFirstHeader("Content-Type"); if (contentType != null) { - memeType = contentType.getValue().split(";")[0].trim(); + return contentType.getValue().split(";")[0].trim(); } - return memeType; + return ""; } /*** @@ -265,29 +264,9 @@ public class HandlerUtil { resp.setStatus(proxyResponse.getCode()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); resp.setCharacterEncoding(Consts.UTF_8.name()); - JSONObject response = new JSONObject(); - String responseData = proxyResponse.getData(); - - if (!StringUtils.isEmpty(responseData)) { - try { - if (responseData.startsWith("{")) { - JSONObject responseDataJsonObj = new JSONObject(responseData); - response.put("data", responseDataJsonObj); - } else if (responseData.startsWith("[")) { - JSONArray responseDataJsonArr = new JSONArray(responseData); - response.put("data", responseDataJsonArr); - } else { - log.warn("Response data is not valid json string >> " + responseData); - response.put("data", responseData); - } - } catch (JSONException e) { - log.error("Response data is not passable"); - response.put("data", responseData); - } - } try (PrintWriter writer = resp.getWriter()) { - writer.write(response.toString()); + writer.write(proxyResponse.getData().toString()); } } @@ -362,7 +341,21 @@ public class HandlerUtil { boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System. getProperty("org.wso2.ignoreHostnameVerification")); if (isIgnoreHostnameVerification) { - return HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); + try { + return HttpClients.custom() + .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create() + .setSslContext(SSLContextBuilder.create() + .loadTrustMaterial(TrustAllStrategy.INSTANCE) + .build()) + .setHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .build()) + .build()) + .build(); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { + log.error("Error Occurred while creating the custom http client", e); + throw new RuntimeException(e); + } } else { return HttpClients.createDefault(); } @@ -413,13 +406,13 @@ public class HandlerUtil { * @throws FileUploadException If unable to parse the incoming request for multipart content extraction. * @throws IOException If error occurred while generating the request body. */ - public static void generateRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) + public static void generateRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest) throws FileUploadException, IOException { if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List fileItemList = servletFileUpload.parseRequest(req); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); - entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + entityBuilder.setMode(HttpMultipartMode.LEGACY); for (FileItem item : fileItemList) { if (!item.isFormField()) { entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(), @@ -434,7 +427,7 @@ public class HandlerUtil { if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), - Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); + Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType())); proxyRequest.setEntity(new BufferedHttpEntity(entity)); } HandlerUtil.copyRequestHeaders(req, proxyRequest, true); @@ -448,12 +441,12 @@ public class HandlerUtil { * @param proxyRequest proxy request instance. * @throws IOException If error occurred while generating the request body. */ - public static void generateChatRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) + public static void generateChatRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest) throws IOException { if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), - Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); + Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType())); proxyRequest.setEntity(new BufferedHttpEntity(entity)); } } @@ -464,17 +457,30 @@ public class HandlerUtil { * @param tags - tags which are retrieved by reading app manager configuration * @param username - username provided from login form or admin username * @param password - password provided from login form or admin password + * @param callbackUrl - callback url + * @param supportedGrantTypes - supported grant types * @return {@link StringEntity} of the payload to create the client application */ - public static StringEntity constructAppRegPayload(JsonArray tags, String appName, String username, String password) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty(HandlerConstants.APP_NAME_KEY, appName); - jsonObject.addProperty(HandlerConstants.USERNAME, username); - jsonObject.addProperty(HandlerConstants.PASSWORD, password); - jsonObject.addProperty(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false"); - jsonObject.add(HandlerConstants.TAGS_KEY, tags); - String payload = jsonObject.toString(); - return new StringEntity(payload, ContentType.APPLICATION_JSON); + public static StringEntity constructAppRegPayload(ArrayNode tags, String appName, String username, String password, + String callbackUrl, ArrayList supportedGrantTypes) { + + ObjectMapper objectMapper = new ObjectMapper(); + Map data = new HashMap<>(); + + data.put(HandlerConstants.APP_NAME_KEY, appName); + data.put(HandlerConstants.USERNAME, username); + data.put(HandlerConstants.PASSWORD, password); + data.put(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false"); + data.put(HandlerConstants.TAGS_KEY, tags); + if (callbackUrl != null) { + data.put(HandlerConstants.CALLBACK_URL_KEY, callbackUrl); + } + if (supportedGrantTypes != null) { + data.put(HandlerConstants.GRANT_TYPE_KEY, supportedGrantTypes); + + } + + return new StringEntity(objectMapper.valueToTree(data).toString(), ContentType.APPLICATION_JSON); } /*** @@ -484,9 +490,9 @@ public class HandlerUtil { * @param gatewayUrl - gateway endpoint URL * @param httpSession - current active HttpSession * @param resp - HttpServletResponse - * @return {@link JsonObject} of UI configurations + * @return {@link JsonNode} of UI configurations */ - public static JsonObject getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession, + public static JsonNode getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession, HttpServletResponse resp) throws IOException { HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint); @@ -497,39 +503,28 @@ public class HandlerUtil { HandlerUtil.handleError(resp, uiConfigResponse); } - if (uiConfigResponse.getData() == null) { + JsonNode responseData = uiConfigResponse.getData(); + if (responseData == null) { log.error("UI config retrieval is failed, and didn't find UI configuration for App manager."); HandlerUtil.handleError(resp, null); - } - JsonParser jsonParser = new JsonParser(); - - JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData()); - JsonObject uiConfigJsonObject = null; - if (uiConfigJsonElement.isJsonObject()) { - uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject(); - if (uiConfigJsonObject == null) { - log.error( - "Either UI config json element is not an json object or converting rom json element to json object is failed."); - HandlerUtil.handleError(resp, null); - } - httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject); + } else { + httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, responseData); httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl); } - return uiConfigJsonObject; + return responseData; } /*** * Converts scopes from JsonArray to string with space separated values. * - * @param scopes - scope Json Array and it is retrieved by reading UI config. + * @param scopes - scope Array and it is retrieved by reading UI config. * @return string value of the defined scopes */ - public static String getScopeString(JsonArray scopes) { - if (scopes != null && scopes.size() > 0) { + public static String getScopeString(JsonNode scopes) { + if (scopes != null && scopes.isArray() && !scopes.isEmpty()) { StringBuilder builder = new StringBuilder(); - for (JsonElement scope : scopes) { - String tmpScope = scope.getAsString() + " "; - builder.append(tmpScope); + for (JsonNode objNode : scopes) { + builder.append(objNode).append(" "); } return builder.toString(); } else { @@ -537,35 +532,6 @@ public class HandlerUtil { } } - /*** - * Converts xml file into string. - * - * @param xmlFile - xmlFile which needs to be converted into string. - * @return string value of the xml file. - */ - public static String xmlToString(File xmlFile) { - String stringOutput = null; - - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(xmlFile); - OutputFormat format = new OutputFormat(doc); - StringWriter stringWriterOutput = new StringWriter(); - XMLSerializer serial = new XMLSerializer(stringWriterOutput, format); - serial.serialize(doc); - stringOutput = stringWriterOutput.toString(); - } catch (IOException e) { - log.error("Error occurred while sending the response into the socket. ", e); - } catch (ParserConfigurationException e) { - log.error("Error while creating the document builder."); - } catch (SAXException e) { - log.error("Error while parsing xml file.", e); - } - - return stringOutput; - } - /*** * Search a key from a given json string object. * @@ -608,11 +574,11 @@ public class HandlerUtil { * Retry request again after refreshing the access token * * @param req incoming {@link HttpServletRequest} - * @param httpRequest subclass of {@link HttpRequestBase} related to the current request. + * @param httpRequest {@link ClassicHttpRequest} related to the current request. * @return {@link ProxyResponse} if successful and null if failed. * @throws IOException If an error occurs when try to retry the request. */ - public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, + public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, ClassicHttpRequest httpRequest, String apiEndpoint) throws IOException { ProxyResponse retryResponse = refreshToken(req, apiEndpoint); if (isResponseSuccessful(retryResponse)) { @@ -628,7 +594,6 @@ public class HandlerUtil { return proxyResponse; } return proxyResponse; - } return retryResponse; } @@ -650,7 +615,6 @@ public class HandlerUtil { if (session == null) { log.error("Couldn't find a session, hence it is required to login and proceed."); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED); -// handleError(resp, HttpStatus.SC_UNAUTHORIZED); return tokenResultResponse; } @@ -658,23 +622,20 @@ public class HandlerUtil { tokenResultResponse = getTokenResult(authData, keymanagerUrl); if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { log.error("Error occurred while refreshing access token."); -// HandlerUtil.handleError(resp, tokenResultResponse); return tokenResultResponse; } - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); - - if (jTokenResult.isJsonObject()) { - setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session); + JsonNode tokenResponse = tokenResultResponse.getData(); + if (tokenResponse != null) { + setNewAuthData(constructAuthDataFromTokenResult(tokenResponse, authData), session); return tokenResultResponse; } log.error("Error Occurred in token renewal process."); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); -// handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR); return tokenResultResponse; } + public static ProxyResponse getTokenResult(AuthData authData, String keymanagerUrl) throws IOException { HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); StringEntity tokenEndpointPayload = new StringEntity( @@ -694,12 +655,17 @@ public class HandlerUtil { session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData); } - public static AuthData constructAuthDataFromTokenResult(JsonElement tokenResult, AuthData authData) { - JsonObject jTokenResultAsJsonObject = tokenResult.getAsJsonObject(); + /** + * Construct {@link AuthData} from token response + * @param tokenResult {@link JsonNode} + * @param authData {@link AuthData} existing auth data values + * @return new {@link AuthData} object + */ + public static AuthData constructAuthDataFromTokenResult(JsonNode tokenResult, AuthData authData) { AuthData newAuthData = new AuthData(); - newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); - newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); - newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); + newAuthData.setAccessToken(tokenResult.get("access_token").textValue()); + newAuthData.setRefreshToken(tokenResult.get("refresh_token").textValue()); + newAuthData.setScope(tokenResult.get("scope").textValue()); newAuthData.setClientId(authData.getClientId()); newAuthData.setClientSecret(authData.getClientSecret()); newAuthData.setEncodedClientApp(authData.getEncodedClientApp()); @@ -716,7 +682,7 @@ public class HandlerUtil { * This should be set to false when handling multipart requests as Http * client will generate the Content-Type header automatically. */ - public static void copyRequestHeaders(HttpServletRequest req, HttpRequestBase httpRequest, boolean preserveContentType) { + public static void copyRequestHeaders(HttpServletRequest req, ClassicHttpRequest httpRequest, boolean preserveContentType) { Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); @@ -742,18 +708,6 @@ public class HandlerUtil { return headerValue; } - public static String getResponseString(HttpResponse response) throws IOException { - try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { - StringBuilder responseBuilder = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - responseBuilder.append(line); - } - return responseBuilder.toString(); - } - } - - public static boolean isPropertyDefined(String property) { return StringUtils.isEmpty(System.getProperty(property)); } diff --git a/components/ui-request-interceptor/pom.xml b/components/ui-request-interceptor/pom.xml index 5a5ef82b68..7436102e2b 100644 --- a/components/ui-request-interceptor/pom.xml +++ b/components/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml index e697ebe9b6..86da566d3c 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index f973ae7dae..9678bff1eb 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -74,7 +74,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { } try { String bearerToken = getBearerToken(request); - bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); +// bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); String resource = requestUri + ":" + requestMethod; OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource); authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo); diff --git a/components/webapp-authenticator-framework/pom.xml b/components/webapp-authenticator-framework/pom.xml index 9e81164345..f51fa10990 100644 --- a/components/webapp-authenticator-framework/pom.xml +++ b/components/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml index d5856bf8a4..b755950ebb 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml index 434a554741..947821bf76 100644 --- a/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml +++ b/features/analytics-mgt/grafana-mgt/io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core grafana-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/grafana-mgt/pom.xml b/features/analytics-mgt/grafana-mgt/pom.xml index 907c8e8c75..6bdd7d18d0 100644 --- a/features/analytics-mgt/grafana-mgt/pom.xml +++ b/features/analytics-mgt/grafana-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core analytics-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/analytics-mgt/pom.xml b/features/analytics-mgt/pom.xml index f7eaeaeef9..6707746cca 100644 --- a/features/analytics-mgt/pom.xml +++ b/features/analytics-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml index 14ba988b93..6f02c2f2aa 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension.feature/pom.xml @@ -20,7 +20,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml index 1b5def60d3..f076c81431 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml index 9ac48cd779..1bd33f2ec3 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml index b64fc605b0..c549b3be86 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.keymgt.extension.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml index c324ec0f69..05283c03d9 100644 --- a/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml +++ b/features/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core apimgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/apimgt-extensions/pom.xml b/features/apimgt-extensions/pom.xml index 6185c6e717..b4fb9e69d0 100644 --- a/features/apimgt-extensions/pom.xml +++ b/features/apimgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml index 2f97648a4f..0b364295f2 100644 --- a/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml +++ b/features/application-mgt/io.entgra.device.mgt.core.application.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core application-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/application-mgt/pom.xml b/features/application-mgt/pom.xml index b64abe8da0..e4f033f192 100644 --- a/features/application-mgt/pom.xml +++ b/features/application-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml index 8a657b1c99..db732a6d2b 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml index 62f45f14ec..82d37fe887 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.cert.admin.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml index 3b0db3bc67..8863c75961 100644 --- a/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml +++ b/features/certificate-mgt/io.entgra.device.mgt.core.certificate.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core certificate-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/certificate-mgt/pom.xml b/features/certificate-mgt/pom.xml index 2569c1e359..4618914050 100644 --- a/features/certificate-mgt/pom.xml +++ b/features/certificate-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml index ddaee9f6de..7b77bd8ace 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml index e357207773..b05a3d31ab 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.type.deployer.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml index 217ec3584d..18df1b5358 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.logger.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml index edbc130ef2..6e829765e6 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml index f0ccefe68d..7ff642d57c 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.http.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml index e629f48373..14b83bc04b 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.mqtt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml index 81199586f5..e49f55820a 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.xmpp.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml index 94a86548d7..032cbbaa4c 100644 --- a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-extensions-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml new file mode 100644 index 0000000000..4d0b62fb18 --- /dev/null +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/pom.xml @@ -0,0 +1,105 @@ + + + + + + + io.entgra.device.mgt.core + device-mgt-extensions-feature + 5.0.33-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.feature + pom + Entgra IoT - User store role mapper feature + http://entgra.io + + This feature contains the core bundles required for user store role mapping functionality + + + + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper + ../../etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + + org.eclipse.equinox.p2.type.group:true + + + + + + io.entgra.device.mgt.core:io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper:${io.entgra.device.mgt.core.version} + + + + + + + + + diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/build.properties b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/build.properties new file mode 100644 index 0000000000..89aee3ff76 --- /dev/null +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/build.properties @@ -0,0 +1,19 @@ +# +# Copyright (c) 2018 - 2023, 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. +# + +custom = true diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/conf/user-store-role-mapping-config.xml b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/conf/user-store-role-mapping-config.xml new file mode 100644 index 0000000000..16316f47ad --- /dev/null +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/conf/user-store-role-mapping-config.xml @@ -0,0 +1,35 @@ + + + + false + 30 + 3600 + + + + Internal/branch_css + + + + + Internal/branch_css + + + + \ No newline at end of file diff --git a/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/p2.inf b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/p2.inf new file mode 100644 index 0000000000..31d07a5e20 --- /dev/null +++ b/features/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper/src/main/resources/p2.inf @@ -0,0 +1,2 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper_${feature.version}/conf/user-store-role-mapping-config.xml,target:${installFolder}/../../../repository/conf/user-store-role-mapping-config.xml,overwrite:true);\ diff --git a/features/device-mgt-extensions/pom.xml b/features/device-mgt-extensions/pom.xml index 5b1f2d321a..47a06ac33a 100644 --- a/features/device-mgt-extensions/pom.xml +++ b/features/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml @@ -41,6 +41,7 @@ io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager.feature io.entgra.device.mgt.core.device.mgt.extensions.logger.feature io.entgra.device.mgt.core.device.mgt.extensions.stateengine.feature + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml index fe04b7692c..198adbfddc 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml index 74e160d442..e249015039 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index 28114158a9..416c0711f3 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -197,6 +197,7 @@ and:enterprise:view dm:sign-csr dm:admin:devices:view + dm:devices:status:change rm:roles:add rm:users:add rm:roles:update diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml index 6380d8e790..8adf83d43e 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml index 2e6fce0d35..0ed24bb713 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml index a72a21fbbe..1383db9420 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core device-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/device-mgt/pom.xml b/features/device-mgt/pom.xml index 040af5111a..78cf21afa0 100644 --- a/features/device-mgt/pom.xml +++ b/features/device-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml index 10d1a4e1ff..0ab11a9b1d 100644 --- a/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.device.mgt.core.server.heart.beat.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core heart-beat-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 4d2ab7d267..46e9e1f913 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml index a99f12315b..f8fcfa3f88 100644 --- a/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml +++ b/features/jwt-client/io.entgra.device.mgt.core.identity.jwt.client.extension.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core jwt-client-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/jwt-client/pom.xml b/features/jwt-client/pom.xml index f4a32ee6af..68ad0eae27 100644 --- a/features/jwt-client/pom.xml +++ b/features/jwt-client/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml index bd5400e510..0b346e2432 100644 --- a/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml +++ b/features/logger/io.entgra.device.mgt.core.notification.logger.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core logger-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/logger/pom.xml b/features/logger/pom.xml index bedf8aac4b..f75cc1a71c 100644 --- a/features/logger/pom.xml +++ b/features/logger/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml index 851a7d5509..abf9a9f9df 100644 --- a/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/io.entgra.device.mgt.core.operation.template.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core operation-template-mgt-plugin-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/operation-template-mgt-plugin-feature/pom.xml b/features/operation-template-mgt-plugin-feature/pom.xml index a3791b2afd..f407363faa 100644 --- a/features/operation-template-mgt-plugin-feature/pom.xml +++ b/features/operation-template-mgt-plugin-feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml index 108ee60d0d..4fd15f93db 100644 --- a/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml +++ b/features/policy-mgt/io.entgra.device.mgt.core.policy.mgt.server.feature/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core policy-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/policy-mgt/pom.xml b/features/policy-mgt/pom.xml index c7762786d0..14db7b6de2 100644 --- a/features/policy-mgt/pom.xml +++ b/features/policy-mgt/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml index 2df461bcd7..5e98534247 100644 --- a/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml +++ b/features/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../../pom.xml diff --git a/features/subtype-mgt/pom.xml b/features/subtype-mgt/pom.xml index 3d388bd0b6..4779be9e5b 100644 --- a/features/subtype-mgt/pom.xml +++ b/features/subtype-mgt/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml index 60af9a0bb4..501ca7c31b 100755 --- a/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml +++ b/features/task-mgt/io.entgra.device.mgt.core.task.mgt.feature/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../../pom.xml diff --git a/features/task-mgt/pom.xml b/features/task-mgt/pom.xml index fca80b6ce9..cab67f5419 100755 --- a/features/task-mgt/pom.xml +++ b/features/task-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml index 9b90307dd6..13747f5783 100644 --- a/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml +++ b/features/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.server.feature/pom.xml @@ -20,7 +20,7 @@ tenant-mgt-feature io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/tenant-mgt/pom.xml b/features/tenant-mgt/pom.xml index 6007c3d4af..81fd1eca0b 100644 --- a/features/tenant-mgt/pom.xml +++ b/features/tenant-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml index ab4a1627a5..20d1da3250 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core email-sender-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm index befc2b3241..be994a117f 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/share-product-download-url.vm @@ -16,46 +16,1981 @@ under the License. *# - Experience Entgra IoT Server + Experience Entgra UEM Server - - Entgra IoT Server - - -
-
-
-
- entgra -
-
-
-

- Hi $first-name, -

-

- Thank you very much for your interest in the Entgra IoT server. Please click - here to download the latest release of the Entgra IoT server.

- -

- If you need assistance, please contact us through Entgra - contact us -

- -

- Regards, -

- -

- Entgra IoT Administrator -

-
-
-
- + + + + + + + + Entgra UEM Server + + + + + + + + + + + + + + +
+ +
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+
+

Hi $first-name,

+

+

Welcome to your free Entgra UEM trial. Please download the product here.

+
+

To make the best use of your evaluation, here's a quick introduction to the key capabilities of our product.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+

Getting started

+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Self-guided enrollment

+
+
+ + + + + + +
+
+

Wizard-based, simple, and clear directions for the best mode of enrollment suited for your requirements.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Guided UI tour

+

+
+
+ + + + + + +
+
+

Guided walkthrough of Entgra UEM for quick navigation of available
features and functionalities.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Live chat

+

+
+
+ + + + + + +
+
+

Instant access to our support team to get answers to your questions.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+

Remote administration

+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Zero-touch enrollment

+
+
+ + + + + + +
+
+

Enroll, administer, and manage your entire device fleet remotely. Find out how to do so here.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Hierarchical grouping

+
+
+ + + + + + +
+
+

Create groups and subgroups in a hierarchical manner via our enhanced UI functionality.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Trigger operations simultaneously in a device group

+
+
+ + + + + + +
+
+

Enforce one or more operations on individual devices of an entire device group at once.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Enforceable policies for device administration

+
+
+ + + + + + + + +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Geofencing and alerts

+

+
+
+ + + + + + + + +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+

UI, analytics, reporting, and real-time processing

+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Reporting UI capabilities +

+

real-time event processing

+
+
+ + + + + + +
+
+

Demonstrative reporting UI
with a set of pre-built reports useful for EMM administration. Enables real-time complex event processing and an

+

in-house solution for batch processing so that you can create customized reports.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Grafana-based dashboards

+

+
+
+ + + + + + +
+
+

Analytics capabilities and dashboards showing useful information on devices, users, applications, operations, and policies.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Live feed

+
+
+ + + + + + +
+
+

Live feed is now available remotely for system administrators to access and track device data remotely, plus perform troubleshooting in real-time.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Per-tenant theming

+
+
+ + + + + + +
+
+

Customize your branding assets such as logos, favicons, app title/footer, etc. for a unified, personalized experience.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+

Security, privacy, and compliance

+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

GDPR compliance

+
+
+ + + + + + +
+
+

Compliant with GDPR.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Consent management

+
+
+ + + + + + +
+
+

Requires the consent of authoritative parties when signing in to the platform and enrolling devices. Cookie and privacy policies in the device management console for consent.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Device protection and security

+
+
+ + + + + + +
+
+

Fetch the device location and/or lock the device remotely. Configure devices in a manner that they become locked when passcode fail attempts exceed the limit. Offline unenrollment is possible via a special admin PIN code per device.

+
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+
+

Additional data protection

+
+
+ + + + + + +
+
+

Use enterprise-wipe to delete the enterprise portion of a device in case of device loss or theft. Clear app data of corporate apps remotely. Lock-in
devices to a given WiFi network to ensure adherence to data protection compliance regulations.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+

More resources

+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+ + +
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+ +
+ + + Blog + + +
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + + + + + + + + +
+ + +
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+
+

That’s Entgra UEM in a nutshell. Reach out to us at evaluations@entgra.io if you have any questions.

+


Thanks for taking the time to explore Entgra UEM’s capabilities.

+


Entgra team

+
+
+ + + + + + +
+ + + + + + +
+ &#160; +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ +
+ + + + + + +
+
+

Follow Entgra on social media

+
+
+ + + + + + +
+
+
+ + + + + + + + +
+ + Facebook + +
+ + + + + + + + +
+ + LinkedIn + +
+ + + + + + + + +
+ + X + +
+ + + + + + + + +
+ + YouTube + +
+ + +
+
+
+ +
+ +
+
+ + +
+
+
+ +
+ + + ]]> -
+ \ No newline at end of file diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-verify.vm b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-verify.vm index bccc1cc0e0..c053cd889b 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-verify.vm +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-verify.vm @@ -16,47 +16,430 @@ under the License. *# - Verify email to register with Entgra IoTS + Verify Email to Register with Entgra UEM Server - - Entgra IoT Server - - -
-
-
-
- entgra -
-
-
-

- Hi $first-name, -

-

- Congratulations!!! Thank you for registering with Entgra. Please click on the - following link to complete your registration with us. Click here. -

- -

- If you need further assistance, please contact your administrator. -

- -

- Regards, -

- -

- Entgra IoT Administrator -

-
-
-
- + + + + + + + + Entgra UEM Server + + + + + + + + + + + + + + +
+ +
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+
+

Hi $first-name,

+


Thanks for your interest in Entgra. Please click here to complete your registration.

+


Once you verify your email address, you can check out all the features of our product.

+


Do get in touch with your administrator for any assistance at evaluations@entgra.io

+


Best wishes,
Entgra team

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ +
+ + + + + + +
+
+

Follow Entgra on social media

+
+
+ + + + + + +
+
+
+ + + + + + + + +
+ + Facebook + +
+ + + + + + + + +
+ + LinkedIn + +
+ + + + + + + + +
+ + X + +
+ + + + + + + + +
+ + YouTube + +
+ + +
+
+
+ +
+ +
+
+ + +
+
+
+ +
+ + + ]]> -
+ \ No newline at end of file diff --git a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-welcome.vm b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-welcome.vm index 7560594911..e8302f9ca9 100644 --- a/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-welcome.vm +++ b/features/transport-mgt/email-sender/io.entgra.device.mgt.core.email.sender.feature/src/main/resources/email/templates/user-welcome.vm @@ -19,80 +19,904 @@ Welcome to Entgra Evaluation Cloud - - Entgra IoT Server - - -
-
-
-
- entgra -
-
-
-

- Hi $first-name, -

-
-

- Welcome to Entgra Evaluation Cloud!! Entgra server support offers managing Android, iOS and Windows - devices along with a wide range of features that support cooperate (COPE) or personal device (BYOD) - enrollments. -

-
-
-

Access different portals

-

Your log-in credentials to any of our portals(endpoint-mgt, store, publisher) are,

-

Username: $portal-username

-

Password: password provided at registration for an evaluation account.

-

Endpoint management portal URL: $base-url-https/endpoint-mgt/

-

- This is the portal used to send operations and policies to devices and overall management of - the server. -

-

Application store portal URL: $base-url-https/store

-

- This is an in-house corporate app store where you can host all your corporate applications. - Users may browse apps and install them to their devices if the administrator has made the apps - publicly visible to users. Administrator can install, uninstall and update apps in the user - device or device groups. -

-

Application publishing portal URL: $base-url-https/publisher

-

- The portal for publishing new applications for internal use. This is the developer view of the - enterprise application store that comes with the product. -

-
-
-

Enroll a device

-

- Please find here a set of videos on how to enroll and onboard devices to our Cloud platform. - [Cloud Enrollment Guide] - When enrolling a device, Make sure to use the following log-in format: -

-

Organisation: $tenant-domain

-

Username: $agent-username

-

Password: password provided at registration.

-
-
-

- If you have any further questions, please reach out to us using your registered mail to - bizdev-group@entgra.io. Looking forward to working with you. -

-

- Best Regards, -

-

- Entgra Cloud Team -

-
-
+ + + + + + + + Entgra UEM Server + + + + + + + + + + + +
+ +
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+
+

Hi $first-name,

+

+

Thanks for registering for a free 14-day Entgra Cloud trial.

+

Entgra enables you to manage Android, iOS, and Windows devices. Our product also has a wide range of capabilities for corporate-owned (COPE) and personal device (BYOD) enrollments.

+


Listed below are some instructions to guide you.

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+

How to Access Our Portals

+
+ + + + + + +
+
+

Please use the following log-in credentials to access any of our portals.

+


Username: $portal-username
Password: Password provided at registration

+
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + +
+
+

Endpoint Management Portal

+
+
+ + + + + + +
+
+

Send operations and apply policies to devices and overall management of the server.

+
+
+ + + + + + +
+ + +
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+
+

Application Store Portal

+
+
+ + + + + + +
+
+

In-house corporate app store to host all your corporate applications. You can browse apps and install them on your devices if the apps are publicly visible to users. Administrators can install, uninstall, and update apps on devices or device groups.

+
+
+ + + + + + +
+ + +
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ + + + +
+ +
+
+ +
+ +
+
+ + +
+
+ +
+ + + + + + + +
+ + + + + + +
+ &#160; +
+
+ + + + + + +
+
+

Application Publishing Portal

+
+
+ + + + + + +
+
+

Publish new applications for internal use. This portal gives you a developer's view of the enterprise application store that comes with the product.

+
+
+ + + + + + +
+ + +
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+

How to Enroll a Device

+
+ + + + + + +
+
+

Here's the comprehensive guide to enrolling and onboarding devices.

+


View guide

+


For questions, contact us at evaluations@entgra.io from your Entgra registered email address.

+


We hope you found this guide helpful and look forward to learning more about your experiences with Entgra.

+

+


Best wishes,
Entgra team

+
+
+ + + + + + +
+ + + + + + +
+ &#160; +
+
+ +
+ +
+
+ + +
+
+
+
+
+
+ + +
+
+ +
+ + + + + + + +
+ +
+ + + + + + +
+
+

Follow Entgra on social media

+
+
+ + + + + + +
+
+
+ + + + + + + + +
+ + Facebook + +
+ + + + + + + + +
+ + LinkedIn + +
+ + + + + + + + +
+ + X + +
+ + + + + + + + +
+ + YouTube + +
+ + +
+
+
+ +
+ +
+
+ + +
+
+
+ +
+ + + ]]> - + \ No newline at end of file diff --git a/features/transport-mgt/email-sender/pom.xml b/features/transport-mgt/email-sender/pom.xml index 7bea1a0af6..a738d2b98b 100644 --- a/features/transport-mgt/email-sender/pom.xml +++ b/features/transport-mgt/email-sender/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/pom.xml b/features/transport-mgt/pom.xml index 2403e63301..42b1152bdf 100644 --- a/features/transport-mgt/pom.xml +++ b/features/transport-mgt/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml index 6f8e76a66e..f9f5e75ce6 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.api.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml index 4b908eb03f..fa1bd1502c 100644 --- a/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml +++ b/features/transport-mgt/sms-handler/io.entgra.device.mgt.core.transport.mgt.sms.handler.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core sms-handler-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/transport-mgt/sms-handler/pom.xml b/features/transport-mgt/sms-handler/pom.xml index f5209b00b5..3e0056956b 100644 --- a/features/transport-mgt/sms-handler/pom.xml +++ b/features/transport-mgt/sms-handler/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core transport-mgt-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml index 014bf54fd9..629d760ec1 100644 --- a/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml +++ b/features/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor.feature/pom.xml @@ -21,7 +21,7 @@ ui-request-interceptor-feature io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT 4.0.0 diff --git a/features/ui-request-interceptor/pom.xml b/features/ui-request-interceptor/pom.xml index 0c614753c6..676aa56e23 100644 --- a/features/ui-request-interceptor/pom.xml +++ b/features/ui-request-interceptor/pom.xml @@ -21,7 +21,7 @@ io.entgra.device.mgt.core.parent io.entgra.device.mgt.core - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml index ddac272f6f..2dd50a95e0 100644 --- a/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml +++ b/features/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework.server.feature/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core webapp-authenticator-framework-feature - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../pom.xml diff --git a/features/webapp-authenticator-framework/pom.xml b/features/webapp-authenticator-framework/pom.xml index 1de6a5a14b..d0a7f1de5d 100644 --- a/features/webapp-authenticator-framework/pom.xml +++ b/features/webapp-authenticator-framework/pom.xml @@ -22,7 +22,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index e29e90df97..3e3ed2bd3b 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.parent pom - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT WSO2 Carbon - Device Management - Parent https://entgra.io WSO2 Connected Device Manager Components @@ -594,7 +594,6 @@ - org.testng testng @@ -1310,8 +1309,8 @@ ${github.openfeign.version} - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 ${apache.http.client.version} @@ -1524,6 +1523,11 @@ io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager ${io.entgra.device.mgt.core.version} + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper + ${io.entgra.device.mgt.core.version} + io.entgra.device.mgt.core io.entgra.device.mgt.core.device.mgt.extensions.logger @@ -1998,7 +2002,7 @@ 1.2.11-wso2v25 - 5.0.31-SNAPSHOT + 5.0.33-SNAPSHOT 4.9.2 @@ -2050,7 +2054,7 @@ 11.0 1.1.1 1.2 - 4.5.13 + 5.2.1 4.4.13 4.5.10