Improvements in App registration

apim420
Pasindu Rupasinghe 1 year ago
parent ac0ba00707
commit cc6bbf1435

@ -26,7 +26,6 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.API
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.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.KeyManager;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Subscription; import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Subscription;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.TokenInfo;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException; 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.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.Metadata;
@ -96,12 +95,11 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
boolean isMappingRequired) boolean isMappingRequired)
throws APIManagerException { throws APIManagerException {
TokenInfo tokenInfo = new TokenInfo(); ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo();
if (StringUtils.isEmpty(accessToken)) { if (StringUtils.isEmpty(accessToken)) {
ApiApplicationInfo applicationInfo = getApplicationInfo(username, password); apiApplicationInfo = getApplicationInfo(username, password);
tokenInfo.setApiApplicationInfo(applicationInfo);
} else { } else {
tokenInfo.setAccessToken(accessToken); apiApplicationInfo.setAccess_token(accessToken);
} }
ConsumerRESTAPIServices consumerRESTAPIServices = ConsumerRESTAPIServices consumerRESTAPIServices =
@ -118,16 +116,16 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
Map<String, String> queryParams = new HashMap<>(); Map<String, String> queryParams = new HashMap<>();
queryParams.put("tag", tag); queryParams.put("tag", tag);
APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(tokenInfo, queryParams, headerParams); APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(apiApplicationInfo, queryParams, headerParams);
Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo)); Arrays.stream(apiInfos).forEach(apiInfo -> uniqueApiSet.putIfAbsent(apiInfo.getName(), apiInfo));
} }
List<APIInfo> uniqueApiList = new ArrayList<>(uniqueApiSet.values()); List<APIInfo> uniqueApiList = new ArrayList<>(uniqueApiSet.values());
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(tokenInfo, applicationName); consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName);
if (applications.length == 0) { if (applications.length == 0) {
return handleNewAPIApplication(applicationName, uniqueApiList, tokenInfo, keyType, return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType,
validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); validityTime, supportedGrantTypes, callbackUrl, isMappingRequired);
} else { } else {
if (applications.length == 1) { if (applications.length == 1) {
@ -140,17 +138,17 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
Metadata metaData = metadataManagementService.retrieveMetadata(applicationName); Metadata metaData = metadataManagementService.retrieveMetadata(applicationName);
if (metaData == null) { if (metaData == null) {
// Todo add a comment // Todo add a comment
consumerRESTAPIServices.deleteApplication(tokenInfo, application.getApplicationId()); consumerRESTAPIServices.deleteApplication(apiApplicationInfo, application.getApplicationId());
return handleNewAPIApplication(applicationName, uniqueApiList, tokenInfo, keyType, return handleNewAPIApplication(applicationName, uniqueApiList, apiApplicationInfo, keyType,
validityTime, supportedGrantTypes, callbackUrl, isMappingRequired); validityTime, supportedGrantTypes, callbackUrl, isMappingRequired);
} else { } else {
Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(tokenInfo, application.getApplicationId()); Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(apiApplicationInfo, application.getApplicationId());
for (Subscription subscription : subscriptions) { for (Subscription subscription : subscriptions) {
uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId())); uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId()));
} }
if (!uniqueApiList.isEmpty()) { if (!uniqueApiList.isEmpty()) {
addSubscriptions(application, uniqueApiList, tokenInfo); addSubscriptions(application, uniqueApiList, apiApplicationInfo);
} }
String[] metaValues = metaData.getMetaValue().split(":"); String[] metaValues = metaData.getMetaValue().split(":");
@ -162,7 +160,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
String applicationId = metaValues[0]; String applicationId = metaValues[0];
String keyMappingId = metaValues[1]; String keyMappingId = metaValues[1];
ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(tokenInfo, applicationId, keyMappingId); ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(apiApplicationInfo, applicationId, keyMappingId);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
@ -195,7 +193,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
private ApiApplicationKey handleNewAPIApplication(String applicationName, List<APIInfo> uniqueApiList, private ApiApplicationKey handleNewAPIApplication(String applicationName, List<APIInfo> uniqueApiList,
TokenInfo tokenInfo, String keyType, String validityTime, ApiApplicationInfo apiApplicationInfo, String keyType, String validityTime,
ArrayList<String> supportedGrantTypes, String callbackUrl, ArrayList<String> supportedGrantTypes, String callbackUrl,
boolean isMappingRequired) throws APIManagerException { boolean isMappingRequired) throws APIManagerException {
ConsumerRESTAPIServices consumerRESTAPIServices = ConsumerRESTAPIServices consumerRESTAPIServices =
@ -205,10 +203,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
application.setThrottlingPolicy(UNLIMITED_TIER); application.setThrottlingPolicy(UNLIMITED_TIER);
try { try {
application = consumerRESTAPIServices.createApplication(tokenInfo, application); application = consumerRESTAPIServices.createApplication(apiApplicationInfo, application);
addSubscriptions(application, uniqueApiList, tokenInfo); addSubscriptions(application, uniqueApiList, apiApplicationInfo);
KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(tokenInfo); KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(apiApplicationInfo);
KeyManager keyManager; KeyManager keyManager;
if (keyManagers.length == 1) { if (keyManagers.length == 1) {
keyManager = keyManagers[0]; keyManager = keyManagers[0];
@ -219,21 +217,29 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
throw new APIManagerException(msg); throw new APIManagerException(msg);
} }
tokenInfo.setApiApplicationInfo(getApplicationInfo(null, null));
ApplicationKey applicationKey; ApplicationKey applicationKey;
if (isMappingRequired) { if (isMappingRequired) {
// If we need to get opaque token instead of the JWT token, we have to do the mapping. Therefore,, if // 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. // it is a requirement then we have to call the method with enabling the flag.
applicationKey = consumerRESTAPIServices.mapApplicationKeys(tokenInfo, application, APIApplicationServices apiApplicationServices = APIApplicationManagerExtensionDataHolder.getInstance()
keyManager.getName(), keyType); .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 { } else {
applicationKey = consumerRESTAPIServices.generateApplicationKeys(tokenInfo, application.getApplicationId(), applicationKey = consumerRESTAPIServices.generateApplicationKeys(apiApplicationInfo, application.getApplicationId(),
keyManager.getName(), validityTime, keyType); keyManager.getName(), validityTime, keyType);
} }
if (supportedGrantTypes != null || StringUtils.isNotEmpty(callbackUrl)) { if (supportedGrantTypes != null || StringUtils.isNotEmpty(callbackUrl)) {
applicationKey = consumerRESTAPIServices.updateGrantType(tokenInfo, application.getApplicationId(), applicationKey = consumerRESTAPIServices.updateGrantType(apiApplicationInfo, application.getApplicationId(),
applicationKey.getKeyMappingId(), keyManager.getName(), supportedGrantTypes, callbackUrl); applicationKey.getKeyMappingId(), keyManager.getName(), supportedGrantTypes, callbackUrl);
} }
@ -277,16 +283,16 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
/** /**
* This method can be used to add a new subscriptions providing the ids of the APIs and the applications. * 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 application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application}
* @param apiInfos {@link List<APIInfo>} * @param apiInfos {@link List<APIInfo>}
* @param tokenInfo {@link TokenInfo} * @param apiApplicationInfo {@link ApiApplicationInfo}
* @throws BadRequestException if incorrect data provided to call subscribing REST API. * @throws BadRequestException if incorrect data provided to call subscribing REST API.
* @throws UnexpectedResponseException if error occurred while processing the 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. * @throws APIServicesException if error occurred while invoking the subscribing REST API.
*/ */
private void addSubscriptions( private void addSubscriptions(
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application, io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application,
List<APIInfo> apiInfos, TokenInfo tokenInfo) List<APIInfo> apiInfos, ApiApplicationInfo apiApplicationInfo)
throws BadRequestException, UnexpectedResponseException, APIServicesException { throws BadRequestException, UnexpectedResponseException, APIServicesException {
ConsumerRESTAPIServices consumerRESTAPIServices = ConsumerRESTAPIServices consumerRESTAPIServices =
@ -302,7 +308,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
subscriptionList.add(subscription); subscriptionList.add(subscription);
}); });
consumerRESTAPIServices.createSubscriptions(tokenInfo, subscriptionList); consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, subscriptionList);
} }
@Override @Override
@ -407,7 +413,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
"ClientForConsumerRestCalls", "ClientForConsumerRestCalls",
"client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer");
} else { } else {
apiApplicationKey = apiApplicationServices.generateAndRetrieveApplicationKeys( apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentialsWithUser(
"ClientForConsumerRestCalls", "ClientForConsumerRestCalls",
username, password, username, password,
"client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer"); "client_credentials password refresh_token urn:ietf:params:oauth:grant-type:jwt-bearer");

@ -27,7 +27,7 @@ public interface APIApplicationServices {
APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType) APIApplicationKey createAndRetrieveApplicationCredentials(String clientName, String grantType)
throws APIServicesException; throws APIServicesException;
APIApplicationKey generateAndRetrieveApplicationKeys(String clientName, String username, String password, String grantType) APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType)
throws APIServicesException; throws APIServicesException;
AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException;

@ -75,7 +75,7 @@ public class APIApplicationServicesImpl implements APIApplicationServices {
} }
@Override @Override
public APIApplicationKey generateAndRetrieveApplicationKeys(String clientName, String username, String password, String grantType) public APIApplicationKey createAndRetrieveApplicationCredentialsWithUser(String clientName, String username, String password, String grantType)
throws APIServicesException { throws APIServicesException {
String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT);

@ -19,7 +19,7 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api; 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.bean.APIMConsumer.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.TokenInfo; 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.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; 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.exceptions.UnexpectedResponseException;
@ -28,43 +28,45 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public interface ConsumerRESTAPIServices { public interface ConsumerRESTAPIServices {
Application[] getAllApplications(TokenInfo tokenInfo, String appName)
Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Application getDetailsOfAnApplication(TokenInfo tokenInfo, String applicationId) Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Application createApplication(TokenInfo tokenInfo, Application application) Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Boolean deleteApplication(TokenInfo tokenInfo, String applicationId) Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription[] getAllSubscriptions(TokenInfo tokenInfo, String applicationId) Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
APIInfo[] getAllApis(TokenInfo tokenInfo, Map<String, String> queryParams, Map<String, String> headerParams) APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription createSubscription(TokenInfo tokenInfo, Subscription subscriptions) Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
Subscription[] createSubscriptions(TokenInfo tokenInfo, List<Subscription> subscriptions) Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey generateApplicationKeys(TokenInfo tokenInfo, String applicationId, String keyManager, String validityTime, String keyType) ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager,
String validityTime, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey mapApplicationKeys(TokenInfo tokenInfo, Application application, String keyManager, String keyType) ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey getKeyDetails(TokenInfo tokenInfo, String applicationId, String keyMapId) ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
ApplicationKey updateGrantType(TokenInfo tokenInfo, String applicationId, String keyMapId, String keyManager, ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager,
List<String> supportedGrantTypes, String callbackUrl) List<String> supportedGrantTypes, String callbackUrl)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
KeyManager[] getAllKeyManagers(TokenInfo tokenInfo) KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
} }

@ -23,7 +23,6 @@ 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.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.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.ApiApplicationInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.TokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; 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.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
@ -51,22 +50,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
+ Constants.COLON + port; + Constants.COLON + port;
@Override @Override
public Application[] getAllApplications(TokenInfo tokenInfo, String appName) public Application[] getAllApplications(ApiApplicationInfo apiApplicationInfo, String appName)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getAllApplicationsUrl = endPointPrefix + Constants.APPLICATIONS_API + "?query=" + appName; String getAllApplicationsUrl = endPointPrefix + Constants.APPLICATIONS_API + "?query=" + appName;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getAllApplicationsUrl); builder.url(getAllApplicationsUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.get(); builder.get();
Request request = builder.build(); Request request = builder.build();
@ -76,21 +68,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
JSONArray applicationList = (JSONArray) new JSONObject(response.body().string()).get("list"); JSONArray applicationList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(applicationList.toString(), Application[].class); return gson.fromJson(applicationList.toString(), Application[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getAllApplications(refreshedApiApplicationInfo, appName);
//TODO: max attempt count //TODO: max attempt count
tokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
tokenInfo.setAccessToken(null);
return getAllApplications(tokenInfo, appName);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -107,22 +91,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Application getDetailsOfAnApplication(TokenInfo tokenInfo, String applicationId) public Application getDetailsOfAnApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getDetailsOfAPPUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; String getDetailsOfAPPUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getDetailsOfAPPUrl); builder.url(getDetailsOfAPPUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.get(); builder.get();
Request request = builder.build(); Request request = builder.build();
@ -131,22 +108,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), Application.class); return gson.fromJson(response.body().string(), Application.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getDetailsOfAnApplication(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return getDetailsOfAnApplication(refreshedTokenInfo, applicationId);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -163,33 +131,38 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Application createApplication(TokenInfo tokenInfo, Application application) public Application createApplication(ApiApplicationInfo apiApplicationInfo, Application application)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API; String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API;
String applicationInfo = "{\n" + JSONArray groups = new JSONArray();
" \"name\": \"" + application.getName() + "\",\n" + JSONArray subscriptionScope = new JSONArray();
" \"throttlingPolicy\": \"" + application.getThrottlingPolicy() + "\",\n" +
" \"description\": \"" + application.getDescription() + "\",\n" + if (application.getGroups() != null && application.getSubscriptionScopes() != null) {
" \"tokenType\": \"" + application.getTokenType() + "\",\n" + for (String string : application.getGroups()) {
" \"groups\": " + gson.toJson(application.getGroups()) + ",\n" + groups.put(string);
" \"attributes\": " + gson.toJson(application.getAttributes()) + ",\n" + }
" \"subscriptionScopes\": " + gson.toJson(application.getSubscriptionScopes()) + "\n" + for (Scopes string : application.getSubscriptionScopes()) {
"}"; subscriptionScope.put(string);
RequestBody requestBody = RequestBody.create(JSON, applicationInfo); }
}
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(); Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl); builder.url(getAllScopesUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.post(requestBody); builder.post(requestBody);
Request request = builder.build(); Request request = builder.build();
@ -198,22 +171,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_CREATED == response.code()) { if (HttpStatus.SC_CREATED == response.code()) {
return gson.fromJson(response.body().string(), Application.class); return gson.fromJson(response.body().string(), Application.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return createApplication(refreshedApiApplicationInfo, application);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return createApplication(refreshedTokenInfo, application);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -230,22 +194,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Boolean deleteApplication(TokenInfo tokenInfo, String applicationId) public Boolean deleteApplication(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String deleteScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId; String deleteScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(deleteScopesUrl); builder.url(deleteScopesUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.delete(); builder.delete();
Request request = builder.build(); Request request = builder.build();
@ -254,22 +211,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return true; return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return deleteApplication(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return deleteApplication(refreshedTokenInfo, applicationId);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -286,22 +234,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Subscription[] getAllSubscriptions(TokenInfo tokenInfo, String applicationId) public Subscription[] getAllSubscriptions(ApiApplicationInfo apiApplicationInfo, String applicationId)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getAllScopesUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "?applicationId=" + applicationId + "&limit=1000"; String getAllScopesUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "?applicationId=" + applicationId + "&limit=1000";
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl); builder.url(getAllScopesUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.get(); builder.get();
Request request = builder.build(); Request request = builder.build();
@ -311,22 +252,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
JSONArray subscriptionList = (JSONArray) new JSONObject(response.body().string()).get("list"); JSONArray subscriptionList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(subscriptionList.toString(), Subscription[].class); return gson.fromJson(subscriptionList.toString(), Subscription[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getAllSubscriptions(refreshedApiApplicationInfo, applicationId);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return getAllSubscriptions(refreshedTokenInfo, applicationId);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -343,11 +275,9 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public APIInfo[] getAllApis(TokenInfo tokenInfo, Map<String, String> queryParams, Map<String, String> headerParams) public APIInfo[] getAllApis(ApiApplicationInfo apiApplicationInfo, Map<String, String> queryParams, Map<String, String> headerParams)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API); StringBuilder getAPIsURL = new StringBuilder(endPointPrefix + Constants.DEV_PORTAL_API);
for (Map.Entry<String, String> query : queryParams.entrySet()) { for (Map.Entry<String, String> query : queryParams.entrySet()) {
@ -356,13 +286,9 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getAPIsURL.toString()); builder.url(getAPIsURL.toString());
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
for (Map.Entry<String, String> header : headerParams.entrySet()) { for (Map.Entry<String, String> header : headerParams.entrySet()) {
builder.addHeader(header.getKey(), header.getValue()); builder.addHeader(header.getKey(), header.getValue());
} }
@ -375,22 +301,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list"); JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(apiList.toString(), APIInfo[].class); return gson.fromJson(apiList.toString(), APIInfo[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getAllApis(refreshedApiApplicationInfo, queryParams, headerParams);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return getAllApis(refreshedTokenInfo, queryParams, headerParams);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -407,31 +324,24 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Subscription createSubscription(TokenInfo tokenInfo, Subscription subscriptions) public Subscription createSubscription(ApiApplicationInfo apiApplicationInfo, Subscription subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String createSubscriptionUrl = endPointPrefix + Constants.SUBSCRIPTION_API; String createSubscriptionUrl = endPointPrefix + Constants.SUBSCRIPTION_API;
String subscriptionObject = "{\n" + JSONObject subscriptionObject = new JSONObject();
" \"applicationId\": \"" + subscriptions.getApplicationId() + "\",\n" + subscriptionObject.put("applicationId", subscriptions.getApplicationId());
" \"apiId\": \"" + subscriptions.getApiId() + "\",\n" + subscriptionObject.put("apiId", subscriptions.getApiId());
" \"throttlingPolicy\": \"" + subscriptions.getThrottlingPolicy() + "\",\n" + subscriptionObject.put("throttlingPolicy", subscriptions.getThrottlingPolicy());
" \"requestedThrottlingPolicy\": \"" + subscriptions.getRequestedThrottlingPolicy() + "\"\n" + subscriptionObject.put("requestedThrottlingPolicy", subscriptions.getRequestedThrottlingPolicy());
"}";
RequestBody requestBody = RequestBody.create(JSON, subscriptionObject); RequestBody requestBody = RequestBody.create(JSON, subscriptionObject.toString());
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(createSubscriptionUrl); builder.url(createSubscriptionUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.post(requestBody); builder.post(requestBody);
Request request = builder.build(); Request request = builder.build();
@ -440,22 +350,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_CREATED == response.code()) { if (HttpStatus.SC_CREATED == response.code()) {
return gson.fromJson(response.body().string(), Subscription.class); return gson.fromJson(response.body().string(), Subscription.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return createSubscription(refreshedApiApplicationInfo, subscriptions);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return createSubscription(refreshedTokenInfo, subscriptions);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -472,11 +373,9 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public Subscription[] createSubscriptions(TokenInfo tokenInfo, List<Subscription> subscriptions) public Subscription[] createSubscriptions(ApiApplicationInfo apiApplicationInfo, List<Subscription> subscriptions)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String createSubscriptionsUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "/multiple"; String createSubscriptionsUrl = endPointPrefix + Constants.SUBSCRIPTION_API + "/multiple";
String subscriptionsList = gson.toJson(subscriptions); String subscriptionsList = gson.toJson(subscriptions);
@ -484,13 +383,9 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(createSubscriptionsUrl); builder.url(createSubscriptionsUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.post(requestBody); builder.post(requestBody);
Request request = builder.build(); Request request = builder.build();
@ -499,22 +394,12 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), Subscription[].class); return gson.fromJson(response.body().string(), Subscription[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return createSubscriptions(refreshedApiApplicationInfo, subscriptions);
//TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return createSubscriptions(refreshedTokenInfo, subscriptions);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -531,42 +416,36 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public ApplicationKey generateApplicationKeys(TokenInfo tokenInfo, String applicationId, String keyManager, public ApplicationKey generateApplicationKeys(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyManager,
String validityTime, String keyType) String validityTime, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String generateApplicationKeysUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + String generateApplicationKeysUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH +
applicationId + "/generate-keys"; applicationId + "/generate-keys";
String keyInfo = "{\n" + JSONArray grantTypesToBeSupported = new JSONArray();
" \"keyType\": \"" + keyType + "\",\n" + grantTypesToBeSupported.put("password");
" \"keyManager\": \"" + keyManager + "\",\n" + grantTypesToBeSupported.put("client_credentials");
" \"grantTypesToBeSupported\": [\n" +
" \"password\",\n" + JSONArray scopes = new JSONArray();
" \"client_credentials\"\n" + scopes.put("am_application_scope");
" ],\n" + scopes.put("default");
" \"callbackUrl\": \"\",\n" +
" \"scopes\": [\n" + JSONObject keyInfo = new JSONObject();
" \"am_application_scope\",\n" + keyInfo.put("keyType", keyType);
" \"default\"\n" + keyInfo.put("keyManager", keyManager);
" ],\n" + keyInfo.put("grantTypesToBeSupported", grantTypesToBeSupported);
" \"validityTime\": " + validityTime + ",\n" + keyInfo.put("callbackUrl", "");
" \"additionalProperties\": {}\n" + keyInfo.put("scopes", scopes);
"}"; keyInfo.put("validityTime", 3600);
keyInfo.put("additionalProperties", new JSONObject());
RequestBody requestBody = RequestBody.create(JSON, keyInfo);
RequestBody requestBody = RequestBody.create(JSON, keyInfo.toString());
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(generateApplicationKeysUrl); builder.url(generateApplicationKeysUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.post(requestBody); builder.post(requestBody);
Request request = builder.build(); Request request = builder.build();
@ -575,22 +454,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class); return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return generateApplicationKeys(refreshedApiApplicationInfo, applicationId, keyManager, validityTime, keyType);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return generateApplicationKeys(refreshedTokenInfo, applicationId, keyManager, validityTime, keyType);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -607,31 +477,24 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public ApplicationKey mapApplicationKeys(TokenInfo tokenInfo, Application application, String keyManager, String keyType) public ApplicationKey mapApplicationKeys(ApiApplicationInfo apiApplicationInfo, Application application, String keyManager, String keyType)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + String getAllScopesUrl = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH +
application.getApplicationId() + "/map-keys"; application.getApplicationId() + "/map-keys";
String payload = "{\n" + JSONObject payload = new JSONObject();
" \"consumerKey\": \"" + apiApplicationInfo.getClientId() + "\",\n" + payload.put("consumerKey", apiApplicationInfo.getClientId());
" \"consumerSecret\": \"" + apiApplicationInfo.getClientSecret() + "\",\n" + payload.put("consumerSecret", apiApplicationInfo.getClientSecret());
" \"keyManager\": \"" + keyManager + "\",\n" + payload.put("keyManager", keyManager);
" \"keyType\": \"" + keyType + "\"\n" + payload.put("keyType", keyType);
"}";
RequestBody requestBody = RequestBody.create(JSON, payload); RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getAllScopesUrl); builder.url(getAllScopesUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.post(requestBody); builder.post(requestBody);
Request request = builder.build(); Request request = builder.build();
@ -640,22 +503,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class); return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return mapApplicationKeys(refreshedApiApplicationInfo, application, keyManager, keyType);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return mapApplicationKeys(refreshedTokenInfo, application, keyManager, keyType);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request body"; String msg = "Bad Request, Invalid request body";
log.error(msg); log.error(msg);
@ -672,22 +526,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public ApplicationKey getKeyDetails(TokenInfo tokenInfo, String applicationId, String keyMapId) public ApplicationKey getKeyDetails(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getKeyDetails); builder.url(getKeyDetails);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.get(); builder.get();
Request request = builder.build(); Request request = builder.build();
@ -696,22 +543,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class); return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getKeyDetails(refreshedApiApplicationInfo, applicationId, keyMapId);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return getKeyDetails(refreshedTokenInfo, applicationId, keyMapId);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -728,23 +566,16 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public ApplicationKey updateGrantType(TokenInfo tokenInfo, String applicationId, String keyMapId, String keyManager, public ApplicationKey updateGrantType(ApiApplicationInfo apiApplicationInfo, String applicationId, String keyMapId, String keyManager,
List<String> supportedGrantTypes, String callbackUrl) List<String> supportedGrantTypes, String callbackUrl)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId; String getKeyDetails = endPointPrefix + Constants.APPLICATIONS_API + Constants.SLASH + applicationId + "/oauth-keys/" + keyMapId;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getKeyDetails); builder.url(getKeyDetails);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
JSONArray supportedGrantTypeList = new JSONArray(); JSONArray supportedGrantTypeList = new JSONArray();
for (String string : supportedGrantTypes) { for (String string : supportedGrantTypes) {
@ -768,22 +599,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), ApplicationKey.class); return gson.fromJson(response.body().string(), ApplicationKey.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return updateGrantType(refreshedApiApplicationInfo, applicationId, keyMapId, keyManager, supportedGrantTypes, callbackUrl);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return updateGrantType(refreshedTokenInfo, applicationId, keyMapId, keyManager, supportedGrantTypes, callbackUrl);
} else {
String msg = "Invalid access token. Unauthorized request";
log.error(msg);
throw new APIServicesException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -800,22 +622,15 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
@Override @Override
public KeyManager[] getAllKeyManagers(TokenInfo tokenInfo) public KeyManager[] getAllKeyManagers(ApiApplicationInfo apiApplicationInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
ApiApplicationInfo apiApplicationInfo = tokenInfo.getApiApplicationInfo();
boolean token = isTokenNull(apiApplicationInfo, tokenInfo.getAccessToken());
String getAllKeyManagersUrl = endPointPrefix + Constants.KEY_MANAGERS_API; String getAllKeyManagersUrl = endPointPrefix + Constants.KEY_MANAGERS_API;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
builder.url(getAllKeyManagersUrl); builder.url(getAllKeyManagersUrl);
if (!token) { builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + apiApplicationInfo.getAccess_token());
+ apiApplicationInfo.getAccess_token());
} else {
builder.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ tokenInfo.getAccessToken());
}
builder.get(); builder.get();
Request request = builder.build(); Request request = builder.build();
@ -825,22 +640,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
JSONArray keyManagerList = (JSONArray) new JSONObject(response.body().string()).get("list"); JSONArray keyManagerList = (JSONArray) new JSONObject(response.body().string()).get("list");
return gson.fromJson(keyManagerList.toString(), KeyManager[].class); return gson.fromJson(keyManagerList.toString(), KeyManager[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
if (!token) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices.
AccessTokenInfo refreshedAccessToken = apiApplicationServices. generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(),
generateAccessTokenFromRefreshToken(apiApplicationInfo.getRefresh_token(), apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret());
apiApplicationInfo.getClientId(), apiApplicationInfo.getClientSecret()); ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken);
ApiApplicationInfo refreshedApiApplicationInfo = returnApplicationInfo(apiApplicationInfo, refreshedAccessToken); return getAllKeyManagers(refreshedApiApplicationInfo);
//TODO: max attempt count //TODO: max attempt count
TokenInfo refreshedTokenInfo = new TokenInfo();
refreshedTokenInfo.setApiApplicationInfo(refreshedApiApplicationInfo);
refreshedTokenInfo.setAccessToken(null);
return getAllKeyManagers(refreshedTokenInfo);
} else {
String msg = "Invalid or null access token";
log.error(msg);
throw new BadRequestException(msg);
}
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) { } else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
@ -856,29 +662,13 @@ public class ConsumerRESTAPIServicesImpl implements ConsumerRESTAPIServices {
} }
} }
private ApiApplicationInfo returnApplicationInfo(ApiApplicationInfo refreshedApplicationInfo, AccessTokenInfo refreshedToken) { private ApiApplicationInfo returnApplicationInfo(ApiApplicationInfo apiApplicationInfo, AccessTokenInfo refreshedToken) {
ApiApplicationInfo applicationInfo = null; ApiApplicationInfo applicationInfo = new ApiApplicationInfo();
applicationInfo.setClientId(refreshedApplicationInfo.getClientId()); applicationInfo.setClientId(apiApplicationInfo.getClientId());
applicationInfo.setClientSecret(refreshedApplicationInfo.getClientSecret()); applicationInfo.setClientSecret(apiApplicationInfo.getClientSecret());
applicationInfo.setAccess_token(refreshedToken.getAccess_token()); applicationInfo.setAccess_token(refreshedToken.getAccess_token());
applicationInfo.setRefresh_token(refreshedToken.getRefresh_token()); applicationInfo.setRefresh_token(refreshedToken.getRefresh_token());
return applicationInfo; return applicationInfo;
} }
private boolean isTokenNull(ApiApplicationInfo apiApplicationInfo, String accessToken) throws BadRequestException {
boolean token;
if ((!(accessToken == null))) {
token = true;
} else if (!(apiApplicationInfo == null) && accessToken == null) {
token = false;
} else {
String msg = "Null access token or Rest Application info";
log.error(msg);
throw new BadRequestException(msg);
}
return token;
}
} }

@ -1,44 +0,0 @@
/*
* 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 information and access token for REST APIS cals.
*/
public class TokenInfo {
private ApiApplicationInfo apiApplicationInfo;
private String accessToken;
public ApiApplicationInfo getApiApplicationInfo() {
return apiApplicationInfo;
}
public void setApiApplicationInfo(ApiApplicationInfo apiApplicationInfo) {
this.apiApplicationInfo = apiApplicationInfo;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}

@ -20,7 +20,7 @@ package io.entgra.device.mgt.core.apimgt.keymgt.extension.service;
import com.google.gson.Gson; 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.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.TokenInfo; 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.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; 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.*;
@ -437,14 +437,13 @@ public class KeyMgtServiceImpl implements KeyMgtService {
*/ */
private io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application getApplication(String applicationName, String accessToken) throws KeyMgtException { private io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application getApplication(String applicationName, String accessToken) throws KeyMgtException {
TokenInfo tokenInfo = new TokenInfo(); ApiApplicationInfo apiApplicationInfo = new ApiApplicationInfo();
tokenInfo.setApiApplicationInfo(null); apiApplicationInfo.setAccess_token(accessToken);
tokenInfo.setAccessToken(accessToken);
try { try {
ConsumerRESTAPIServices consumerRESTAPIServices = ConsumerRESTAPIServices consumerRESTAPIServices =
KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices(); KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices();
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(tokenInfo, applicationName); consumerRESTAPIServices.getAllApplications(apiApplicationInfo, applicationName);
if (applications.length == 1) { if (applications.length == 1) {
return applications[0]; return applications[0];
} else { } else {

@ -27,7 +27,6 @@ import io.entgra.device.mgt.core.apimgt.application.extension.internal.APIApplic
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; 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.APIApplicationServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.TokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; 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.DCRResponse;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest; import io.entgra.device.mgt.core.apimgt.keymgt.extension.TokenRequest;
@ -828,8 +827,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
"perm:users:send-invitation"); "perm:users:send-invitation");
APIManagementProviderService apiManagementProviderService = DeviceMgtAPIUtils.getAPIManagementService(); APIManagementProviderService apiManagementProviderService = DeviceMgtAPIUtils.getAPIManagementService();
// TokenInfo tokenInfo = new TokenInfo();
// tokenInfo.setAccessToken(accessTokenInfo.getAccessToken());
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName, apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName,
new String[] {"device_management"}, "PRODUCTION", null, false, String.valueOf(validityTime), new String[] {"device_management"}, "PRODUCTION", null, false, String.valueOf(validityTime),
null, accessTokenInfo.getAccessToken(), null, null,true); null, accessTokenInfo.getAccessToken(), null, null,true);

Loading…
Cancel
Save