Add APIM devportal API integration

pull/306/head
Lasantha Dharmakeerthi 11 months ago
commit 1013831507

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -189,8 +189,8 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>analytics-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -20,7 +20,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -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) {

@ -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<String> 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<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
}

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -79,6 +79,17 @@
<artifactId>io.entgra.device.mgt.core.identity.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
<!-- <scope>provided</scope>-->
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
<!-- <scope>provided</scope>-->
</dependency>
</dependencies>
<build>
@ -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)",

@ -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<String> supportedGrantTypes,
String callbackUrl,
boolean isMappingRequired) throws APIManagerException;
/**
* To get access token for given scopes and for the given validity period

@ -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<String> 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<String, String> headerParams = new HashMap<>();
if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) {
headerParams.put("X-WSO2-Tenant", "carbon.super");
}
Set<SubscribedAPI> subscribedAPIs =
null; // todo:apim - apiConsumer.getSubscribedAPIs(subscriber, applicationName, "");
log.info("Already subscribed API count: " + subscribedAPIs.size());
// subscribe to apis.
Set<String> tempApiIds = new HashSet<>();
APIConsumer apiConsumerAPIPublishedTenant = apiConsumer;
if (tags != null && tags.length > 0) {
for (String tag : tags) {
boolean startedTenantFlow = false;
Set<API> 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<String, APIInfo> uniqueApiSet = new HashMap<>();
for (String tag : tags) {
Map<String, String> 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<ApiTypeWrapper> 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<APIInfo> 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<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> 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<APIKey> 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<APIInfo> uniqueApiList,
ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime,
ArrayList<String> 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<String> 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<KeyManagerConfigurationDTO> 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<String, Object> 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<APIInfo>}
* @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<APIInfo> apiInfos, ApiApplicationInfo apiApplicationInfo)
throws BadRequestException, UnexpectedResponseException, APIServicesException {
ConsumerRESTAPIServices consumerRESTAPIServices =
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
List<Subscription> 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;
}
}

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

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

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

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

@ -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<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> 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<String> supportedGrantTypes, String callbackUrl)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
}

@ -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<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API);
for (Map.Entry<String, String> 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<String, String> 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<Subscription> 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<String> 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;
}
}

@ -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<String> throttlingPolicies;
private JSONObject advertiseInfo;
private JSONObject businessInformation;
private boolean isSubscriptionAvailable;
private String monetizationLabel;
private String gatewayVendor;
private List<String> 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<String> getThrottlingPolicies() {
return throttlingPolicies;
}
public void setThrottlingPolicies(List<String> 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<String> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(List<String> additionalProperties) {
this.additionalProperties = additionalProperties;
}
}

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

@ -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<String> groups;
private int subscriptionCount;
private List<String> keys;
private Map<String, String> attributes;
private List<Scopes> 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<String> getGroups() {
return groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
public int getSubscriptionCount() {
return subscriptionCount;
}
public void setSubscriptionCount(int subscriptionCount) {
this.subscriptionCount = subscriptionCount;
}
public List<String> getKeys() {
return keys;
}
public void setKeys(List<String> keys) {
this.keys = keys;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public List<Scopes> getSubscriptionScopes() {
return subscriptionScopes;
}
public void setSubscriptionScopes(List<Scopes> 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;
}
}

@ -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<String> 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<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
public String getDefaults() {
return defaults;
}
public void setDefaults(String defaults) {
this.defaults = defaults;
}
}

@ -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<String> supportedGrantTypes;
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
public ArrayList<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
}

@ -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<String> 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<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(List<String> 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;
}
}

@ -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<String> 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<ApplicationConfigurations> 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<String> getAvailableGrantTypes() {
return availableGrantTypes;
}
public void setAvailableGrantTypes(List<String> 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<ApplicationConfigurations> getApplicationConfiguration() {
return applicationConfiguration;
}
public void setApplicationConfiguration(List<ApplicationConfigurations> applicationConfiguration) {
this.applicationConfiguration = applicationConfiguration;
}
public JSONObject getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(JSONObject additionalProperties) {
this.additionalProperties = additionalProperties;
}
}

@ -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<String> 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<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

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

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

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

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

@ -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");
}

@ -21,7 +21,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

@ -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<String> 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<String> getSupportedGrantTypes() {
return supportedGrantTypes;
}
public void setSupportedGrantTypes(ArrayList<String> supportedGrantTypes) {
this.supportedGrantTypes = supportedGrantTypes;
}
}

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

@ -21,7 +21,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -55,6 +55,11 @@
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.apimgt.extension.rest.api</artifactId>
<!-- <scope>provided</scope>-->
</dependency>
</dependencies>
<build>
@ -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)",

@ -28,5 +28,9 @@ public class KeyMgtException extends Exception {
public KeyMgtException(String errorMessage) {
super(errorMessage);
}
public KeyMgtException(String errorMessage, Exception e) {
super(errorMessage, e);
}
}

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

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

@ -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<String> supportedGrantTypes, String callbackUrl) throws KeyMgtException;
/***
* This method will handle the access token requests

@ -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<String> 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<String> 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<String> 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();
}

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -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<String> 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<ApiScope> 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<String> 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<String> 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<ApiScope> 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<String> 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<String> 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<String> 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)));

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>application-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>application-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -173,10 +173,9 @@
</build>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>

@ -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<VppUserDTO> users = new ArrayList<>();
List<Device> 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<VppUserDTO> users = new ArrayList<>();
List<Device> 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) {

@ -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();
}

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>certificate-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

@ -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 + "%");

@ -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)) {

@ -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)) {

@ -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)) {

@ -849,6 +849,7 @@ public class CertificateGenerator {
new io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate();
List<io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
certificate.setTenantId(tenantId);
certificate.setDeviceIdentifier(commonName);
certificate.setCertificate(issuedCert);
certificates.add(certificate);
saveCertInKeyStore(certificates);

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

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -0,0 +1,212 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper</artifactId>
<packaging>bundle</packaging>
<name>Entgra IoT - User store role mapping Module</name>
<description>Entgra IoT - User store role mapping Module</description>
<url>http://entgra.io</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${io.entgra.device.mgt.core.version}</Bundle-Version>
<Bundle-Description>IOT - User store role mapping Module</Bundle-Description>
<Private-Package>io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper.internal</Private-Package>
<Import-Package>
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
</Import-Package>
<Export-Package>
!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}"
</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-surefire-plugin</artifactId>-->
<!-- <configuration>-->
<!-- <systemPropertyVariables>-->
<!-- <log4j.configuration>file:src/test/resources/carbon-home/repository/conf/log4j.properties-->
<!-- </log4j.configuration>-->
<!-- </systemPropertyVariables>-->
<!-- <suiteXmlFiles>-->
<!-- <file>src/test/resources/testng.xml</file>-->
<!-- </suiteXmlFiles>-->
<!-- </configuration>-->
<!-- </plugin>-->
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.user.mgt</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.securevault</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.securevault</groupId>
<artifactId>org.wso2.securevault</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xerces.wso2</groupId>
<artifactId>xercesImpl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.server.bootup.heartbeat.beacon</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -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<RoleMapping> 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<String> primaryRoles = mapping.getInternalRoles();
for (String role : primaryRoles) {
if (userStoreManager.isExistingRole(role)) {
String[] existingUsers = userStoreManager.getUserListOfRole(role);
List<String> existingUserList = new ArrayList<>(Arrays.asList(existingUsers));
List<String> 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<String> 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();
}
}
}

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

@ -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<String> 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<String> getInternalRoles() {
return internalRoles;
}
public void setInternalRoles(List<String> internalRoles) {
this.internalRoles = internalRoles;
}
}

@ -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<RoleMapping> 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<RoleMapping> getMappings() {
return mappings;
}
public void setMappings(List<RoleMapping> 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;
}
}

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

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

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

@ -22,7 +22,7 @@
<parent>
<artifactId>io.entgra.device.mgt.core.parent</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@ -43,6 +43,7 @@
<module>io.entgra.device.mgt.core.device.mgt.extensions.logger</module>
<module>io.entgra.device.mgt.core.device.mgt.extensions.defaultrole.manager</module>
<module>io.entgra.device.mgt.core.device.mgt.extensions.stateengine</module>
<module>io.entgra.device.mgt.core.device.mgt.extensions.userstore.role.mapper</module>
</modules>
</project>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

@ -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")

@ -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",

@ -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<DeviceIdentifier> successfullyDisenrolledDevices = new ArrayList<>();
List<DeviceIdentifier> failedToDisenrollDevices = new ArrayList<>();
Map<String, List<String>> list = deviceTypeWithDeviceIds.getDeviceTypeWithDeviceIds();
String deviceType;
List<String> deviceIds;
DeviceIdentifier deviceIdentifier;
Device persistedDevice;
boolean response;
for (Map.Entry<String, List<String>> 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<String, List<DeviceIdentifier>> 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();

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

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

@ -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<String, List<String>> deviceTypeWithDeviceIds;
public Map<String, List<String>> getDeviceTypeWithDeviceIds() {
return deviceTypeWithDeviceIds;
}
public void setDeviceTypeWithDeviceIds(Map<String, List<String>> deviceTypeWithDeviceIds) {
this.deviceTypeWithDeviceIds = deviceTypeWithDeviceIds;
}
}

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

@ -21,7 +21,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -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();
}

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

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

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>device-mgt</artifactId>
<version>5.0.31-SNAPSHOT</version>
<version>5.0.33-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

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

@ -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<Device> 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);
}
}
}

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

@ -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<GeofenceData> 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 <GeofenceData> 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);
}
}
}

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

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save