From fa3c112a68dc774fbbb01f1c9537d0d636c48171 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 4 May 2023 16:08:01 +0530 Subject: [PATCH] Implement on progress publisher api layer --- .../pom.xml | 5 + .../rest/api/PublisherRESTAPIServices.java | 51 +- .../api/PublisherRESTAPIServicesImpl.java | 615 +++++++++++++++++- .../rest/api/constants/Constants.java | 4 +- .../extension/rest/api/util/APIUtils.java | 139 ++++ .../publisher/APIPublisherServiceImpl.java | 128 +++- components/apimgt-extensions/pom.xml | 14 + 7 files changed, 918 insertions(+), 38 deletions(-) create mode 100644 components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/APIUtils.java diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml index d5f559ff34..7dd0c74914 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/pom.xml @@ -34,6 +34,11 @@ https://entgra.io + + commons-httpclient.wso2 + commons-httpclient + provided + org.wso2.carbon org.wso2.carbon.logging diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index 2ea0a51f34..e17a480400 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -24,7 +24,9 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIService 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.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.*; + +import java.util.List; public interface PublisherRESTAPIServices { @@ -34,6 +36,53 @@ public interface PublisherRESTAPIServices { boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException; + + API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, String asyncApiDefinition) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean addApiSpecificMediationPolicy (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String action) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + APIRevision addAPIRevision (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevision apiRevision) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean deployAPIRevision (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String apiRevisionId, List apiRevisionDeploymentList) + throws APIServicesException, BadRequestException, UnexpectedResponseException; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java index 819b91210d..19c3c42a01 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java @@ -18,6 +18,7 @@ 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.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; @@ -36,14 +37,16 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.ssl.Base64; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.*; import java.io.IOException; +import java.util.List; public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServicesImpl.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); @@ -94,7 +97,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, Constants.EMPTY_STRING); String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON - + port + Constants.GET_SCOPE + keyValue; + + port + Constants.SCOPE_API_ENDPOINT + keyValue; Request request = new Request.Builder() .url(getScopeUrl) @@ -117,6 +120,58 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); + } else if (HttpStatus.SC_NOT_FOUND == response.code()) { + String msg = "Shared scope key not found"; + log.error(msg); + return false; + } 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(e); + } + } + + @Override + public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId(); + + ScopeUtils scopeUtil = new ScopeUtils(); + scopeUtil.setKey(scope.getKey()); + scopeUtil.setName(scope.getName()); + scopeUtil.setDescription(scope.getDescription()); + scopeUtil.setRoles(scope.getRoles()); + String scopeString = scopeUtil.toJSON(); + + RequestBody requestBody = RequestBody.create(JSON, scopeString); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .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(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + log.error(msg); + throw new BadRequestException(msg); } else { String msg = "Response : " + response.code() + response.body(); throw new UnexpectedResponseException(msg); @@ -133,7 +188,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException { String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); + + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -175,4 +230,558 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throw new APIServicesException(e); } } + + @Override + public API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApis = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + Constants.API_ENDPOINT + apiIdentifier.getUUID(); + Request request = new Request.Builder() + .url(getAllApis) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), API.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return getApi(apiApplicationKey, refreshedAccessToken, apiIdentifier); + } 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(e); + } + } + + @Override + public JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApis = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + + port + Constants.GET_ALL_APIS; + Request request = new Request.Builder() + .url(getAllApis) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return getApis(apiApplicationKey, refreshedAccessToken); + } 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(e); + } + } + + @Override + public API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT; + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); + Request request = new Request.Builder() + .url(updateScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return gson.fromJson(response.body().string(), API.class); + + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return createAPI(apiApplicationKey, refreshedAccessToken, api); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + api.getUuid(); + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); + Request request = new Request.Builder() + .url(updateScopeUrl) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return true; + + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return updateApi(apiApplicationKey, refreshedAccessToken, api); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String asyncApiDefinition) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid; + + + RequestBody requestBody = RequestBody.create(JSON, asyncApiDefinition); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .put(requestBody) + .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(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return saveAsyncApiDefinition(apiApplicationKey, refreshedAccessToken, uuid, asyncApiDefinition); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + + } + + @Override + public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/mediation-policies"; + + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiIdentifier); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() + + "/content"; + + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .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(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + + } + + + @Override + public boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String updateApiSpecificMediationPolicyContentAPI = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() + + "/content"; + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); + Request request = new Request.Builder() + .url(updateApiSpecificMediationPolicyContentAPI) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .put(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_CREATED == response.code()) { + return true; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + + } + + @Override + public boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String action) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid + + "&action=" + action; + + + RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .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(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return changeLifeCycleStatus(apiApplicationKey, refreshedAccessToken, uuid, action); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getLatestRevisionUUIDEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:true"; + + Request request = new Request.Builder() + .url(getLatestRevisionUUIDEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return getAPIRevision(apiApplicationKey, refreshedAccessToken, uuid); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public JSONObject getAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getLatestRevisionUUIDEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/deployments"; + + Request request = new Request.Builder() + .url(getLatestRevisionUUIDEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .get() + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return getAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, uuid); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevision apiRevision) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; + + String apiRevisionDescription = "{\n" + + " \"description\":\" " + apiRevision.getDescription() + "\",\n" + + "}"; + + RequestBody requestBody = RequestBody.create(JSON, apiRevisionDescription); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .build(); + + try { + Response response = client.newCall(request).execute(); + if (HttpStatus.SC_OK == response.code()) { + return gson.fromJson(response.body().string(), APIRevision.class); + } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + AccessTokenInfo refreshedAccessToken = apiApplicationServices. + generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return addAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } + + @Override + public boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String apiRevisionId, List apiRevisionDeploymentList) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + + apiRevisionId; + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeploymentList)); + Request request = new Request.Builder() + .url(addNewScope) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .post(requestBody) + .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(accessTokenInfo.getRefresh_token(), + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + //TODO: max attempt count + return deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId, + apiRevisionDeploymentList); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid scope object"; + 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(e); + } + } } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java index e4dd49b381..d8a12810af 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/constants/Constants.java @@ -61,7 +61,9 @@ public final class Constants { public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; - public static final String GET_SCOPE = "/api/am/publisher/v2/scopes/"; + public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v2/scopes/"; + public static final String API_ENDPOINT = "/api/am/publisher/v2/apis/"; + public static final String GET_ALL_APIS = "/api/am/publisher/v2/apis?limit=1000"; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/APIUtils.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/APIUtils.java new file mode 100644 index 0000000000..b4fa9f73d8 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/APIUtils.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 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.util; + +import org.wso2.carbon.apimgt.api.model.APIIdentifier; + +/** + * This class represents the api data. + */ +public class APIUtils { + + private APIIdentifier id; + private String name; + private String description; + private String context; + private String version; + private String provider; + private String type; + private String lifeCycleStatus; + private String workflowStatus; + private String hasThumbnail; + private String transport; + + public APIIdentifier getId() { + return id; + } + + public void setId(APIIdentifier 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 getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getLifeCycleStatus() { + return lifeCycleStatus; + } + + public void setLifeCycleStatus(String lifeCycleStatus) { + this.lifeCycleStatus = lifeCycleStatus; + } + + public String getWorkflowStatus() { + return workflowStatus; + } + + public void setWorkflowStatus(String workflowStatus) { + this.workflowStatus = workflowStatus; + } + + public String getHasThumbnail() { + return hasThumbnail; + } + + public void setHasThumbnail(String hasThumbnail) { + this.hasThumbnail = hasThumbnail; + } + + public String getTransport() { + return transport; + } + + public void setTransport(String transport) { + this.transport = transport; + } + + public String toJSON() { + String jsonString = "{\n" + + " \"name\":\" " + name + "\",\n" + + " \"description\":\" " + description + "\",\n" + + " \"context\":\" " + context + " \",\n" + + " \"transport\":[\n" + + " \" " + transport + " \"\n" + + " ]\n" + + "}"; + return jsonString; + } +} \ No newline at end of file diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index 52b81fd557..38b19c9061 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -100,6 +100,20 @@ public class APIPublisherServiceImpl implements APIPublisherService { tenants.addAll(config.getTenants().getTenant()); RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() .getOSGiService(RealmService.class, null); + + APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); + APIApplicationKey apiApplicationKey; + AccessTokenInfo accessTokenInfo; + try { + apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); + accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( + apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); + } catch (APIServicesException e) { + String errorMsg = "Error while generating application"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); + } + try { boolean tenantFound = false; boolean tenantsLoaded = false; @@ -140,25 +154,39 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()), apiConfig.getName(), apiConfig.getVersion()); - if (!apiProvider.isAPIAvailable(apiIdentifier)) { + PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); + JSONArray apiList = (JSONArray) publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo).get("list"); + boolean apiFound = false; + + for (int i = 0; i < apiList.length(); i++) { + JSONObject apiObj = apiList.getJSONObject(i); + if (apiObj.getString("name").equals(apiIdentifier.getApiName())){ + apiFound = true; + } + } + if (!apiFound) { // add new scopes as shared scopes - Set allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); for (ApiScope apiScope : apiConfig.getScopes()) { - if (!allSharedScopeKeys.contains(apiScope.getKey())) { +// if (!allSharedScopeKeys.contains(apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { Scope scope = new Scope(); scope.setName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); scope.setRoles(apiScope.getRoles()); - apiProvider.addSharedScope(scope, tenantDomain); +// apiProvider.addSharedScope(scope, tenantDomain); //add scope + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } API api = getAPI(apiConfig, true); api.setId(apiIdentifier); - API createdAPI = apiProvider.addAPI(api); +// API createdAPI = apiProvider.addAPI(api); // add api + API createdAPI = publisherRESTAPIServices.createAPI(apiApplicationKey, accessTokenInfo , api); // add api if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); +// apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); //Update Topics of an Async API + publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, + api.getUuid(), apiConfig.getAsyncApiDefinition()); } if (CREATED_STATUS.equals(createdAPI.getStatus())) { // if endpoint type "dynamic" and then add in sequence @@ -168,14 +196,20 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setType("in"); mediation.setGlobal(false); - apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation, - tenantDomain); +// apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation, +// tenantDomain); //Update an API Specific Mediation Policy + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, createdAPI.getUuid(), mediation); } - apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); +// apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); //Change API Status + publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, createdAPI.getUuid(), PUBLISH_ACTION); + APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(createdAPI.getUuid()); apiRevision.setDescription("Initial Revision"); - String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); +// String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); //Create API Revision + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, + accessTokenInfo, apiRevision).getRevisionUUID(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); @@ -184,7 +218,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); +// apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); //Deploy Revision + publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, + createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { @@ -203,12 +239,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { // 1. add new scopes as shared scopes // 2. update the API adding scopes for the URI Templates - Set allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); +// Set allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); //get all scopes Set scopesToMoveAsSharedScopes = new HashSet<>(); for (ApiScope apiScope : apiConfig.getScopes()) { // if the scope is not available as shared scope and it is assigned to an API as a local scope // need remove the local scope and add as a shared scope - if (!allSharedScopeKeys.contains(apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { +// if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { // collect scope to move as shared scopes scopesToMoveAsSharedScopes.add(apiScope); @@ -219,19 +256,23 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); scope.setRoles(apiScope.getRoles()); - apiProvider.addSharedScope(scope, tenantDomain); +// apiProvider.addSharedScope(scope, tenantDomain); //add scope + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + } } } // Get existing API - API existingAPI = apiProvider.getAPI(apiIdentifier); + API existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier); +// API existingAPI = apiProvider.getAPI(apiIdentifier); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes API api = getAPI(apiConfig, false); api.setStatus(existingAPI.getStatus()); - apiProvider.updateAPI(api); +// apiProvider.updateAPI(api); + publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { Scope scope = new Scope(); @@ -239,17 +280,22 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); scope.setRoles(apiScope.getRoles()); - apiProvider.addSharedScope(scope, tenantDomain); +// apiProvider.addSharedScope(scope, tenantDomain); + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } - existingAPI = apiProvider.getAPI(apiIdentifier); +// existingAPI = apiProvider.getAPI(apiIdentifier); + existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier);; API api = getAPI(apiConfig, true); api.setStatus(existingAPI.getStatus()); - apiProvider.updateAPI(api); +// apiProvider.updateAPI(api); + publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); +// apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, + api.getUuid(), apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -260,35 +306,50 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setType("in"); mediation.setGlobal(false); - List mediationList = apiProvider - .getAllApiSpecificMediationPolicies(apiIdentifier); +// List mediationList = apiProvider +// .getAllApiSpecificMediationPolicies(apiIdentifier); + List mediationList = (List) publisherRESTAPIServices + .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiIdentifier).get("list"); + boolean isMediationPolicyFound = false; for (Mediation m : mediationList) { if (apiConfig.getInSequenceName().equals(m.getName())) { m.setConfig(apiConfig.getInSequenceConfig()); - apiProvider - .updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, - tenantDomain); +// apiProvider +// .updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, +// tenantDomain); + publisherRESTAPIServices. + updateApiSpecificMediationPolicyContent(apiApplicationKey, + accessTokenInfo, existingAPI.getUuid(), m); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { - apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation, - tenantDomain); +// apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation, +// tenantDomain); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, existingAPI.getUuid(), mediation); } } // Assumption: Assume the latest revision is the published one String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); - List latestRevisionDeploymentList = - apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); +// List latestRevisionDeploymentList = +// apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); + List latestRevisionDeploymentList = (List) + publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); + +// List apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); + List apiRevisionList = (List) publisherRESTAPIServices.getAPIRevision(apiApplicationKey, + accessTokenInfo, existingAPI.getUuid()).get("list"); - List apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); if (apiRevisionList.size() >= 5) { String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); - List earliestRevisionDeploymentList = - apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); +// List earliestRevisionDeploymentList = +// apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); + List earliestRevisionDeploymentList = (List) + publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList); apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); } @@ -344,7 +405,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiProvider.addDocumentation(api.getId(), apiDocumentation); apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); } - } catch (FaultGatewaysException | APIManagementException | IOException e) { + } catch (FaultGatewaysException | APIManagementException | IOException | APIServicesException | + BadRequestException | UnexpectedResponseException e) { String msg = "Error occurred while publishing api"; log.error(msg, e); throw new APIManagerPublisherException(e); diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 040f3a9ed0..9739d58d2d 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,6 +25,20 @@ 5.0.26-SNAPSHOT ../../pom.xml + + + com.squareup.okhttp3 + okhttp + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.impl + + 4.0.0 apimgt-extensions