From fa3c112a68dc774fbbb01f1c9537d0d636c48171 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 4 May 2023 16:08:01 +0530 Subject: [PATCH 01/11] 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 From c6b43cc794997c51789378db7b7068bc5370a9bd Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 9 May 2023 14:21:53 +0530 Subject: [PATCH 02/11] Implment API layer for API publisher --- .../rest/api/PublisherRESTAPIServices.java | 58 ++-- .../api/PublisherRESTAPIServicesImpl.java | 283 +++++++++++++++++- .../publisher/APIPublisherServiceImpl.java | 93 ++++-- 3 files changed, 379 insertions(+), 55 deletions(-) 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 e17a480400..29f0b912df 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 @@ -37,7 +37,7 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException; @@ -46,23 +46,23 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + throws APIServicesException, BadRequestException, UnexpectedResponseException; API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, String asyncApiDefinition) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + 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 addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, Mediation mediation) @@ -70,19 +70,43 @@ public interface PublisherRESTAPIServices { boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, String action) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String deploymentStatus) + 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; + 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; + + abstract boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevisionDeployment apiRevisionDeployment, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevision apiRevision, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean deployAPIRevision (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String apiRevisionId, List apiRevisionDeploymentList) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier, String documentID) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier, Documentation documentation) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + API api, String docId, String docContent) + 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 19c3c42a01..591603ef40 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 @@ -139,7 +139,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + String addNewSharedScopeEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); @@ -151,7 +151,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, scopeString); Request request = new Request.Builder() - .url(addNewScope) + .url(addNewSharedScopeEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -167,7 +167,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); + return addNewSharedScope(apiApplicationKey, refreshedAccessToken, scope); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid scope object"; log.error(msg); @@ -552,7 +552,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); + return updateApiSpecificMediationPolicyContent(apiApplicationKey, refreshedAccessToken, uuid, mediation); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid scope object"; log.error(msg); @@ -614,14 +614,15 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String deploymentStatus) + throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getLatestRevisionUUIDEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:true"; + String getAPIRevisionsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions" + deploymentStatus; Request request = new Request.Builder() - .url(getLatestRevisionUUIDEndPoint) + .url(getAPIRevisionsEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .get() @@ -638,7 +639,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return getAPIRevision(apiApplicationKey, refreshedAccessToken, uuid); + return getAPIRevisions(apiApplicationKey, refreshedAccessToken, uuid, deploymentStatus); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid scope object"; log.error(msg); @@ -784,4 +785,266 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throw new APIServicesException(e); } } + + @Override + public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevisionDeployment apiRevisionDeployment, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String apiRevisionEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions/" + + apiRevisionDeployment.getRevisionUUID(); + + RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeployment)); + Request request = new Request.Builder() + .url(apiRevisionEndPoint) + .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 undeployAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, apiRevisionDeployment, 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 boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevision apiRevision, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String apiRevisionEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions/" + + apiRevision.getRevisionUUID(); + + Request request = new Request.Builder() + .url(apiRevisionEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .delete() + .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 deleteAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision, 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 getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDocumentationsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents?limit=1000"; + + Request request = new Request.Builder() + .url(getDocumentationsEndPoint) + .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 getDocumentations(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 deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier, String documentID) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDocumentationsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents/" + documentID; + + Request request = new Request.Builder() + .url(getDocumentationsEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + + accessTokenInfo.getAccess_token()) + .delete() + .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 deleteDocumentations(apiApplicationKey, refreshedAccessToken, apiIdentifier, documentID); + } 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 Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier, Documentation documentation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents"; + + String document = "{\n" + + " \"name\": \" " + documentation.getName() + " \",\n" + + " \"type\": \" " + documentation.getType() + " \",\n" + + " \"summary\": \" " + documentation.getSummary() + " \",\n" + + " \"sourceType\": \" " + documentation.getSourceType() + " \",\n" + + " \"inlineContent\": \" " + documentation.getSourceType() + " \",\n" + + " \"visibility\": \" " + documentation.getVisibility() + " \",\n" + + " \"createdBy\": \" admin \"\n" + + "}"; + + RequestBody requestBody = RequestBody.create(JSON, document); + 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_CREATED == response.code()) { + return gson.fromJson(response.body().string(), Documentation.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 addDocumentation(apiApplicationKey, refreshedAccessToken, apiIdentifier, documentation); + } 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 addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + API api, String docId, String docContent) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port + Constants.API_ENDPOINT + api.getUuid() + "/documents/" + docId; + + RequestBody requestBody = RequestBody.create(JSON, docContent); + 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 addDocumentationContent(apiApplicationKey, refreshedAccessToken, api,docId ,docContent); + } 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.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 38b19c9061..8b54defd83 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 @@ -242,10 +242,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { // 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 + // if the scope is not available as shared scope, and it is assigned to an API as a local scope // need remove the local scope and add as a shared scope if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { -// if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { // collect scope to move as shared scopes scopesToMoveAsSharedScopes.add(apiScope); @@ -315,8 +314,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (Mediation m : mediationList) { if (apiConfig.getInSequenceName().equals(m.getName())) { m.setConfig(apiConfig.getInSequenceConfig()); -// apiProvider -// .updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, +// apiProvider.updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, // tenantDomain); publisherRESTAPIServices. updateApiSpecificMediationPolicyContent(apiApplicationKey, @@ -334,36 +332,59 @@ public class APIPublisherServiceImpl implements APIPublisherService { } // Assumption: Assume the latest revision is the published one - String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); -// List latestRevisionDeploymentList = +// String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); +// List revisionDeploymentList = // apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); - List latestRevisionDeploymentList = (List) + + // This will retrieve the deployed revision list + List revisionDeploymentList = (List) publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); + // This will retrieve the un deployed revision list + List undeployedRevisionList = (List) + publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, + existingAPI.getUuid(), "?query=deployed:false").get("list"); // List apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); - List apiRevisionList = (List) publisherRESTAPIServices.getAPIRevision(apiApplicationKey, - accessTokenInfo, existingAPI.getUuid()).get("list"); - - if (apiRevisionList.size() >= 5) { - String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); -// List earliestRevisionDeploymentList = +// List apiRevisionList = (List) publisherRESTAPIServices.getAPIRevision(apiApplicationKey, +// accessTokenInfo, existingAPI.getUuid()).get("list"); + int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, + accessTokenInfo, existingAPI.getUuid(), "").get("count"); + + if (apiRevisionCount >= 5) { +// String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); +// List undeployedRevisionList = // apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); - List earliestRevisionDeploymentList = (List) - publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); - apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList); - apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); +// List undeployedRevisionList = (List) +// publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); + + APIRevisionDeployment latestRevisionDeployment = revisionDeploymentList.get(0); + APIRevision earliestUndeployRevision = undeployedRevisionList.get(0); + +// apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, undeployedRevisionList); + publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, + accessTokenInfo, latestRevisionDeployment, existingAPI.getUuid()); + +// apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); + publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, + earliestUndeployRevision, existingAPI.getUuid()); } // create new revision APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(existingAPI.getUuid()); apiRevision.setDescription("Updated Revision"); - String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); +// String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, + accessTokenInfo, apiRevision).getRevisionUUID(); - apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, latestRevisionDeploymentList); +// apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, revisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, + existingAPI.getUuid(), apiRevisionId, revisionDeploymentList); if (CREATED_STATUS.equals(existingAPI.getStatus())) { - apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); +// apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); + publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo, + existingAPI.getUuid(), PUBLISH_ACTION); } } } @@ -395,17 +416,33 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setOtherTypeName(null); - try { - //Including below code lines inside the try block because 'getDocumentation' method returns an APIManagementException exception when it doesn't have any existing doc - Documentation existingDoc = apiProvider.getDocumentation(api.getId(), DocumentationType.HOWTO, apiConfig.getApiDocumentationName()); - apiProvider.removeDocumentation(api.getId(), existingDoc.getId(), null); - } catch (APIManagementException e) { + //Including below code lines inside the try block because 'getDocumentation' method returns an APIManagementException exception when it doesn't have any existing doc +// Documentation existingDoc = apiProvider.getDocumentation(api.getId(), DocumentationType.HOWTO, apiConfig.getApiDocumentationName()); + JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey, + accessTokenInfo, api.getId()).get("list"); + + if (!(documentList.length() == 0)) { + for (int i = 0; i < documentList.length(); i++) { + JSONObject existingDoc = documentList.getJSONObject(i); + if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName()) + && existingDoc.getString("type").equals(DocumentationType.HOWTO)) { + //apiProvider.removeDocumentation(api.getId(), existingDoc.getId(), null); + publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, + api.getId(), existingDoc.getString("documentId")); + } + } + } else { log.info("There is no any existing api documentation."); } - apiProvider.addDocumentation(api.getId(), apiDocumentation); - apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); +// apiProvider.addDocumentation(api.getId(), apiDocumentation); + Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, + api.getId(), apiDocumentation); + +// apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); + publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, api, + createdDoc.getId(), docContent); } - } catch (FaultGatewaysException | APIManagementException | IOException | APIServicesException | + } catch (APIManagementException | IOException | APIServicesException | BadRequestException | UnexpectedResponseException e) { String msg = "Error occurred while publishing api"; log.error(msg, e); From a8cc35ef3d966c2354dc5931a925a75d742077d9 Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 9 May 2023 22:27:22 +0530 Subject: [PATCH 03/11] Fix apis --- .../api/PublisherRESTAPIServicesImpl.java | 120 +++++++----------- 1 file changed, 46 insertions(+), 74 deletions(-) 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 591603ef40..2c917a69a2 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 @@ -49,13 +49,13 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { private static final Gson gson = new Gson(); private static final String host = System.getProperty(Constants.IOT_CORE_HOST); private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); + private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + port; @Override public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAllScopesUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON - + port + Constants.GET_ALL_SCOPES; + String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() .url(getAllScopesUrl) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -96,8 +96,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.SCOPE_API_ENDPOINT + keyValue; + String getScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + keyValue; Request request = new Request.Builder() .url(getScopeUrl) @@ -139,8 +138,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewSharedScopeEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId(); + String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -187,8 +185,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId(); + String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -235,8 +232,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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(); + String getAllApis = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID(); Request request = new Request.Builder() .url(getAllApis) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -274,8 +270,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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; + String getAllApis = endPointPrefix + Constants.GET_ALL_APIS; Request request = new Request.Builder() .url(getAllApis) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -314,12 +309,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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; + String creatAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); Request request = new Request.Builder() - .url(updateScopeUrl) + .url(creatAPIEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -356,12 +350,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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(); + String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getUuid(); RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); Request request = new Request.Builder() - .url(updateScopeUrl) + .url(updateAPIEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -399,9 +392,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String uuid, String asyncApiDefinition) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + uuid; - + String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid; RequestBody requestBody = RequestBody.create(JSON, asyncApiDefinition); Request request = new Request.Builder() @@ -413,7 +404,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_OK == response.code()) { //Check the response return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -439,14 +430,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + 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"; + String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/mediation-policies"; Request request = new Request.Builder() - .url(addNewScope) + .url(getAPIMediationEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .get() @@ -484,14 +475,12 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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() + String addAPIMediation = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() + "/content"; - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); Request request = new Request.Builder() - .url(addNewScope) + .url(addAPIMediation) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -499,7 +488,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -530,13 +519,12 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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() + String updateApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid() + "/content"; RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation)); Request request = new Request.Builder() - .url(updateApiSpecificMediationPolicyContentAPI) + .url(updateApiMediationEndPOint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .put(requestBody) @@ -544,7 +532,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -574,14 +562,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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; - + String changeStatusEndPoint = endPointPrefix + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid + "&action=" + action; RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING); Request request = new Request.Builder() - .url(addNewScope) + .url(changeStatusEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -589,7 +574,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_OK == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -618,8 +603,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAPIRevisionsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions" + deploymentStatus; + String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions" + deploymentStatus; Request request = new Request.Builder() .url(getAPIRevisionsEndPoint) @@ -659,8 +643,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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"; + String getLatestRevisionUUIDEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deployments"; Request request = new Request.Builder() .url(getLatestRevisionUUIDEndPoint) @@ -697,12 +680,10 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision) + 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 addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; String apiRevisionDescription = "{\n" + " \"description\":\" " + apiRevision.getDescription() + "\",\n" + @@ -718,7 +699,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return gson.fromJson(response.body().string(), APIRevision.class); } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -747,13 +728,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { 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; + String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeploymentList)); Request request = new Request.Builder() - .url(addNewScope) + .url(deployAPIRevisionEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -761,7 +740,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -791,13 +770,12 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { APIRevisionDeployment apiRevisionDeployment, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String apiRevisionEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions/" + String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + apiRevisionDeployment.getRevisionUUID(); RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeployment)); Request request = new Request.Builder() - .url(apiRevisionEndPoint) + .url(undeployAPIRevisionEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -805,7 +783,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -834,9 +812,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { APIRevision apiRevision, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String apiRevisionEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions/" - + apiRevision.getRevisionUUID(); + String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + apiRevision.getRevisionUUID(); Request request = new Request.Builder() .url(apiRevisionEndPoint) @@ -847,7 +823,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_OK == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -875,8 +851,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getDocumentationsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents?limit=1000"; + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents?limit=1000"; Request request = new Request.Builder() .url(getDocumentationsEndPoint) @@ -917,8 +892,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { APIIdentifier apiIdentifier, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getDocumentationsEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents/" + documentID; + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents/" + documentID; Request request = new Request.Builder() .url(getDocumentationsEndPoint) @@ -958,8 +932,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { APIIdentifier apiIdentifier, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents"; + String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents"; String document = "{\n" + " \"name\": \" " + documentation.getName() + " \",\n" + @@ -981,7 +954,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return gson.fromJson(response.body().string(), Documentation.class); } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -1010,12 +983,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { API api, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host - + Constants.COLON + port + Constants.API_ENDPOINT + api.getUuid() + "/documents/" + docId; + String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getUuid() + "/documents/" + docId; RequestBody requestBody = RequestBody.create(JSON, docContent); Request request = new Request.Builder() - .url(addNewScope) + .url(addDocumentationContentEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -1023,7 +995,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { // Check response status return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); From 65da984f66f899610dfbec81403bcd584b517619 Mon Sep 17 00:00:00 2001 From: pasindu Date: Tue, 9 May 2023 22:27:51 +0530 Subject: [PATCH 04/11] Remove comented code lines --- .../extension/rest/api/util/APIUtils.java | 139 ------------------ .../publisher/APIPublisherServiceImpl.java | 49 ------ components/apimgt-extensions/pom.xml | 14 -- 3 files changed, 202 deletions(-) delete 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/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 deleted file mode 100644 index b4fa9f73d8..0000000000 --- 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 +++ /dev/null @@ -1,139 +0,0 @@ -/* - * 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 8b54defd83..0780a4ad34 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 @@ -36,7 +36,6 @@ import org.json.JSONArray; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; -import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIRevision; @@ -168,23 +167,19 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { -// 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); //add scope publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } API api = getAPI(apiConfig, true); api.setId(apiIdentifier); -// 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()); //Update Topics of an Async API publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, api.getUuid(), apiConfig.getAsyncApiDefinition()); } @@ -196,18 +191,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setType("in"); mediation.setGlobal(false); -// 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); //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); //Create API Revision String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, accessTokenInfo, apiRevision).getRevisionUUID(); @@ -218,7 +209,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); -// apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); //Deploy Revision publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); } @@ -239,7 +229,6 @@ 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); //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 @@ -255,7 +244,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); scope.setRoles(apiScope.getRoles()); -// apiProvider.addSharedScope(scope, tenantDomain); //add scope publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } @@ -264,13 +252,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { // Get existing API 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); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { @@ -279,20 +265,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(apiScope.getDescription()); scope.setKey(apiScope.getKey()); scope.setRoles(apiScope.getRoles()); -// apiProvider.addSharedScope(scope, tenantDomain); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } -// existingAPI = apiProvider.getAPI(apiIdentifier); existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier);; API api = getAPI(apiConfig, true); api.setStatus(existingAPI.getStatus()); -// apiProvider.updateAPI(api); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { -// apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, api.getUuid(), apiConfig.getAsyncApiDefinition()); } @@ -305,8 +287,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setType("in"); mediation.setGlobal(false); -// List mediationList = apiProvider -// .getAllApiSpecificMediationPolicies(apiIdentifier); List mediationList = (List) publisherRESTAPIServices .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiIdentifier).get("list"); @@ -314,8 +294,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (Mediation m : mediationList) { if (apiConfig.getInSequenceName().equals(m.getName())) { m.setConfig(apiConfig.getInSequenceConfig()); -// apiProvider.updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, -// tenantDomain); publisherRESTAPIServices. updateApiSpecificMediationPolicyContent(apiApplicationKey, accessTokenInfo, existingAPI.getUuid(), m); @@ -324,19 +302,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } if (!isMediationPolicyFound) { -// 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 revisionDeploymentList = -// apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); - - // This will retrieve the deployed revision list List revisionDeploymentList = (List) publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); // This will retrieve the un deployed revision list @@ -344,27 +314,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, existingAPI.getUuid(), "?query=deployed:false").get("list"); -// List apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); -// List apiRevisionList = (List) publisherRESTAPIServices.getAPIRevision(apiApplicationKey, -// accessTokenInfo, existingAPI.getUuid()).get("list"); int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, existingAPI.getUuid(), "").get("count"); if (apiRevisionCount >= 5) { -// String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); -// List undeployedRevisionList = -// apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); -// List undeployedRevisionList = (List) -// publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); - APIRevisionDeployment latestRevisionDeployment = revisionDeploymentList.get(0); APIRevision earliestUndeployRevision = undeployedRevisionList.get(0); -// apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, undeployedRevisionList); publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, latestRevisionDeployment, existingAPI.getUuid()); -// apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, earliestUndeployRevision, existingAPI.getUuid()); } @@ -373,16 +332,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(existingAPI.getUuid()); apiRevision.setDescription("Updated Revision"); -// String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, accessTokenInfo, apiRevision).getRevisionUUID(); -// apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, revisionDeploymentList); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, existingAPI.getUuid(), apiRevisionId, revisionDeploymentList); if (CREATED_STATUS.equals(existingAPI.getStatus())) { -// apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo, existingAPI.getUuid(), PUBLISH_ACTION); } @@ -416,8 +372,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setOtherTypeName(null); - //Including below code lines inside the try block because 'getDocumentation' method returns an APIManagementException exception when it doesn't have any existing doc -// Documentation existingDoc = apiProvider.getDocumentation(api.getId(), DocumentationType.HOWTO, apiConfig.getApiDocumentationName()); JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey, accessTokenInfo, api.getId()).get("list"); @@ -426,7 +380,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { JSONObject existingDoc = documentList.getJSONObject(i); if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName()) && existingDoc.getString("type").equals(DocumentationType.HOWTO)) { - //apiProvider.removeDocumentation(api.getId(), existingDoc.getId(), null); publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, api.getId(), existingDoc.getString("documentId")); } @@ -434,11 +387,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { } else { log.info("There is no any existing api documentation."); } -// apiProvider.addDocumentation(api.getId(), apiDocumentation); Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, api.getId(), apiDocumentation); -// apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, api, createdDoc.getId(), docContent); } diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index 9739d58d2d..040f3a9ed0 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -25,20 +25,6 @@ 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 From 7e94f152ea75baa6170f8f84ea76f1480a8f8a94 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 11 May 2023 10:08:16 +0530 Subject: [PATCH 05/11] Remove wild card imports --- .../rest/api/PublisherRESTAPIServices.java | 19 ++++++++++++++----- .../api/PublisherRESTAPIServicesImpl.java | 8 +++++++- 2 files changed, 21 insertions(+), 6 deletions(-) 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 29f0b912df..e129449a8e 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,13 @@ 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.*; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.Mediation; +import org.wso2.carbon.apimgt.api.model.APIRevision; +import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; +import org.wso2.carbon.apimgt.api.model.Documentation; import java.util.List; @@ -54,10 +60,12 @@ public interface PublisherRESTAPIServices { boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, String asyncApiDefinition) + boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String asyncApiDefinition) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, @@ -95,7 +103,8 @@ public interface PublisherRESTAPIServices { APIRevision apiRevision, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, @@ -103,7 +112,7 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier, Documentation documentation) + APIIdentifier apiIdentifier, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, 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 2c917a69a2..b8eaa46985 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 @@ -37,7 +37,13 @@ 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.*; +import org.wso2.carbon.apimgt.api.model.API; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.apimgt.api.model.Mediation; +import org.wso2.carbon.apimgt.api.model.APIRevision; +import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; +import org.wso2.carbon.apimgt.api.model.Documentation; import java.io.IOException; import java.util.List; From cbb03d4d1f69a469e106de65a8ad17430e03909f Mon Sep 17 00:00:00 2001 From: pasindu Date: Mon, 15 May 2023 08:31:57 +0530 Subject: [PATCH 06/11] Minor fixes in api requests --- .../pom.xml | 5 +++ .../rest/api/PublisherRESTAPIServices.java | 2 +- .../api/PublisherRESTAPIServicesImpl.java | 44 ++++++++++++------- .../rest/api/constants/Constants.java | 3 +- .../extension/rest/api/util/ScopeUtils.java | 8 ++-- .../publisher/APIPublisherServiceImpl.java | 16 ++++--- 6 files changed, 48 insertions(+), 30 deletions(-) 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 7dd0c74914..4bb277f623 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 @@ -84,6 +84,11 @@ okhttp compile + + org.wso2.orbit.com.fasterxml.jackson.core + jackson-databind + provided + 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 e129449a8e..a88db1fc6a 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 @@ -54,7 +54,7 @@ public interface PublisherRESTAPIServices { JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException; - API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) 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 b8eaa46985..39a890115f 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 @@ -55,7 +55,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { private static final Gson gson = new Gson(); private static final String host = System.getProperty(Constants.IOT_CORE_HOST); private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); - private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON + port; + private static final String endPointPrefix = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + + Constants.COLON + port; @Override public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) @@ -127,7 +128,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throw new BadRequestException(msg); } else if (HttpStatus.SC_NOT_FOUND == response.code()) { String msg = "Shared scope key not found"; - log.error(msg); + log.info(msg); return false; } else { String msg = "Response : " + response.code() + response.body(); @@ -144,7 +145,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); + String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -163,7 +164,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { + if (HttpStatus.SC_CREATED == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -177,7 +178,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { log.error(msg); throw new BadRequestException(msg); } else { - String msg = "Response : " + response.code() + response.body(); + String msg = "Response : " + response.code() + response.message(); throw new UnexpectedResponseException(msg); } } catch (IOException e) { @@ -312,14 +313,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String creatAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; + String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); + APIIdentifier apiIdentifier = api.getId(); + String apiString = "{\n" + + " \"name\":\"" + apiIdentifier.getName().replace(Constants.SPACE, Constants.EMPTY_STRING) + "\",\n" + + " \"description\":\"" + api.getDescription() + "\",\n" + + " \"context\":\"" + api.getContext() + "\",\n" + + " \"version\":\"" + apiIdentifier.getVersion() + "\"\n" + + "}"; + + RequestBody requestBody = RequestBody.create(JSON, apiString); Request request = new Request.Builder() - .url(creatAPIEndPoint) + .url(addAPIEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -328,21 +337,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); if (HttpStatus.SC_CREATED == response.code()) { - return gson.fromJson(response.body().string(), API.class); - + 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 createAPI(apiApplicationKey, refreshedAccessToken, api); + return addAPI(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(); + String msg = "Response status : " + response.code() + " Response message : " + response.message(); throw new UnexpectedResponseException(msg); } } catch (IOException e) { @@ -568,11 +577,12 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { String uuid, String action) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String changeStatusEndPoint = endPointPrefix + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid + "&action=" + action; + String changeAPIStatusEndPoint = endPointPrefix + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid + + "&action=" + action; RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING); Request request = new Request.Builder() - .url(changeStatusEndPoint) + .url(changeAPIStatusEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .post(requestBody) @@ -986,7 +996,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - API api, String docId, String docContent) + API api, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getUuid() + "/documents/" + docId; @@ -1009,7 +1019,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return addDocumentationContent(apiApplicationKey, refreshedAccessToken, api,docId ,docContent); + return addDocumentationContent(apiApplicationKey, refreshedAccessToken, api, docId, docContent); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { String msg = "Bad Request, Invalid scope object"; log.error(msg); 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 d8a12810af..30074c7b4a 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 @@ -34,7 +34,7 @@ public final class Constants { public static final String OAUTH_TOKEN_TYPE = "token_type"; public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String SCOPE_PARAM_NAME = "scope"; - public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage"; + public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export apim:api_publish"; public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; @@ -58,6 +58,7 @@ public final class Constants { public static final String SCHEME_SEPARATOR = "://"; public static final String COLON = ":"; public static final String QUERY_KEY_VALUE_SEPARATOR = "="; + public static final String SPACE = " "; 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"; 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/ScopeUtils.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/ScopeUtils.java index 18944c945c..a9fa3a3cb9 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/util/ScopeUtils.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/ScopeUtils.java @@ -62,11 +62,11 @@ public class ScopeUtils { public String toJSON() { String jsonString = "{\n" + - " \"name\":\" " + key + "\",\n" + - " \"displayName\":\" " + name + "\",\n" + - " \"description\":\" " + description + " \",\n" + + " \"name\":\"" + key + "\",\n" + + " \"displayName\":\"" + name + "\",\n" + + " \"description\":\"" + description + "\",\n" + " \"bindings\":[\n" + - " \" " + roles + " \"\n" + + " \"" + roles + "\"\n" + " ]\n" + "}"; return jsonString; 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 0780a4ad34..9765e14af8 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 @@ -167,7 +167,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, + apiScope.getKey())) { Scope scope = new Scope(); scope.setName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); @@ -178,12 +179,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { } API api = getAPI(apiConfig, true); api.setId(apiIdentifier); - API createdAPI = publisherRESTAPIServices.createAPI(apiApplicationKey, accessTokenInfo , api); // add api + JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); // add api if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, api.getUuid(), apiConfig.getAsyncApiDefinition()); } - if (CREATED_STATUS.equals(createdAPI.getStatus())) { + if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) { // if endpoint type "dynamic" and then add in sequence if ("dynamic".equals(apiConfig.getEndpointType())) { Mediation mediation = new Mediation(); @@ -192,12 +193,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setType("in"); mediation.setGlobal(false); publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, createdAPI.getUuid(), mediation); + accessTokenInfo, createdAPI.getString("id"), mediation); } - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, createdAPI.getUuid(), PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, + createdAPI.getString("id"), PUBLISH_ACTION); APIRevision apiRevision = new APIRevision(); - apiRevision.setApiUUID(createdAPI.getUuid()); + apiRevision.setApiUUID(createdAPI.getString("id")); apiRevision.setDescription("Initial Revision"); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, accessTokenInfo, apiRevision).getRevisionUUID(); @@ -210,7 +212,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); + createdAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { From a683bd7110c8db80d7294a37719e5bec6b84a1ac Mon Sep 17 00:00:00 2001 From: pasindu Date: Wed, 17 May 2023 10:18:52 +0530 Subject: [PATCH 07/11] Fix API response --- .../rest/api/PublisherRESTAPIServices.java | 28 +- .../api/PublisherRESTAPIServicesImpl.java | 304 +++++++----- .../api/util/APIUtils/APIResponseUtil.java | 460 ++++++++++++++++++ .../rest/api/util/APIUtils/AdvertiseInfo.java | 41 ++ .../util/APIUtils/BusinessInformation.java | 41 ++ .../rest/api/util/APIUtils/Operations.java | 114 +++++ .../extension/rest/api/util/ScopeUtils.java | 6 +- .../pom.xml | 3 + .../publisher/APIPublisherServiceImpl.java | 321 +++++++----- 9 files changed, 1062 insertions(+), 256 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/APIResponseUtil.java 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/AdvertiseInfo.java 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/BusinessInformation.java 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/Operations.java 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 a88db1fc6a..33d124e5fa 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 @@ -23,8 +23,9 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; +import org.json.JSONArray; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.Mediation; @@ -48,16 +49,16 @@ public interface PublisherRESTAPIServices { boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) throws APIServicesException, BadRequestException, UnexpectedResponseException; - API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, @@ -84,11 +85,8 @@ public interface PublisherRESTAPIServices { String deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject getAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; - - APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision) + JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIRevision apiRevision) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, @@ -96,26 +94,26 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; abstract boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevisionDeployment apiRevisionDeployment, String uuid) + JSONObject apiRevisionDeployment, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) + JSONObject apiRevision, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier) + String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier, String documentID) + String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException; Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier, Documentation documentation) + String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - API api, String docId, String docContent) + APIResponseUtil api, String docId, String docContent) 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 39a890115f..bfc2e1661d 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 @@ -25,6 +25,7 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; import okhttp3.MediaType; @@ -36,8 +37,8 @@ import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.ssl.Base64; +import org.json.JSONArray; import org.json.JSONObject; -import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.Mediation; @@ -93,7 +94,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -137,7 +138,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -184,7 +185,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -231,17 +232,17 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override - public API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + public JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAllApis = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID(); + String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID(); Request request = new Request.Builder() - .url(getAllApis) + .url(getAllApi) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) .get() @@ -250,7 +251,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); if (HttpStatus.SC_OK == response.code()) { - return gson.fromJson(response.body().string(), API.class); + JSONObject jsonObject = new JSONObject(response.body().string()); + return jsonObject; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); AccessTokenInfo refreshedAccessToken = apiApplicationServices. @@ -269,7 +271,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -308,22 +310,60 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override - public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; - APIIdentifier apiIdentifier = api.getId(); String apiString = "{\n" + - " \"name\":\"" + apiIdentifier.getName().replace(Constants.SPACE, Constants.EMPTY_STRING) + "\",\n" + + " \"name\": \"" + api.getName() + "\",\n" + " \"description\":\"" + api.getDescription() + "\",\n" + " \"context\":\"" + api.getContext() + "\",\n" + - " \"version\":\"" + apiIdentifier.getVersion() + "\"\n" + + " \"version\":\"" + api.getVersion() + "\",\n" + + " \"provider\":\"" + api.getProvider() + "\",\n" + + " \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" + + " \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" + + " \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" + + " \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" + + " \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" + + " \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" + + " \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" + + " \"isRevision\": " + api.isRevision() + ",\n" + + " \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" + + " \"revisionId\": " + api.getRevisionId() + ",\n" + + " \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" + + " \"type\": \"" + api.getType() + "\",\n" + + " \"transport\": " + gson.toJson(api.getTransport()) + ",\n" + + " \"tags\": " + gson.toJson(api.getTags()) + ",\n" + + " \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" + + " \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + + " \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" + + " \"visibility\": \"" + api.getVisibility() + "\",\n" + + " \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + + " \"subscriptionAvailableTenants\": [],\n" + + " \"additionalProperties\": [],\n" + + " \"monetization\": " + api.getMonetization() + ",\n" + + " \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" + + " \"websubSubscriptionConfiguration\": {\n" + + " \"enable\": false,\n" + + " \"secret\": \"\",\n" + + " \"signingAlgorithm\": \"SHA1\",\n" + + " \"signatureHeader\": \"x-hub-signature\"\n" + + " },\n" + + " \"workflowStatus\": null,\n" + + " \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + + " \"endpointImplementationType\": \"ENDPOINT\",\n" + + " \"scopes\": " + api.getScopes().toString() + ",\n" + + " \"operations\": " + api.getOperations().toString() + ",\n" + + " \"threatProtectionPolicies\": null,\n" + + " \"categories\": [],\n" + + " \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + + " \"serviceInfo\": " + api.getServiceInfo() + "\n" + "}"; RequestBody requestBody = RequestBody.create(JSON, apiString); @@ -347,7 +387,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return addAPI(apiApplicationKey, refreshedAccessToken, api); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid API request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -357,27 +397,73 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override - public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api) + public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getUuid(); + String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api)); + String apiString = "{\n" + + " \"name\": \"" + api.getName() + "\",\n" + + " \"description\":\"" + api.getDescription() + "\",\n" + + " \"context\":\"" + api.getContext() + "\",\n" + + " \"version\":\"" + api.getVersion() + "\",\n" + + " \"provider\":\"" + api.getProvider() + "\",\n" + + " \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" + + " \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" + + " \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" + + " \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" + + " \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" + + " \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" + + " \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" + + " \"isRevision\": " + api.isRevision() + ",\n" + + " \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" + + " \"revisionId\": " + api.getRevisionId() + ",\n" + + " \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" + + " \"type\": \"" + api.getType() + "\",\n" + + " \"transport\": " + gson.toJson(api.getTransport()) + ",\n" + + " \"tags\": " + gson.toJson(api.getTags()) + ",\n" + + " \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" + + " \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + + " \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" + + " \"visibility\": \"" + api.getVisibility() + "\",\n" + + " \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + + " \"subscriptionAvailableTenants\": [],\n" + + " \"additionalProperties\": [],\n" + + " \"monetization\": " + api.getMonetization() + ",\n" + + " \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" + + " \"websubSubscriptionConfiguration\": {\n" + + " \"enable\": false,\n" + + " \"secret\": \"\",\n" + + " \"signingAlgorithm\": \"SHA1\",\n" + + " \"signatureHeader\": \"x-hub-signature\"\n" + + " },\n" + + " \"workflowStatus\": null,\n" + + " \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + + " \"endpointImplementationType\": \"ENDPOINT\",\n" + + " \"scopes\": " + api.getScopes().toString() + ",\n" + + " \"operations\": " + api.getOperations().toString() + ",\n" + + " \"threatProtectionPolicies\": null,\n" + + " \"categories\": [],\n" + + " \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + + " \"serviceInfo\": " + api.getServiceInfo() + "\n" + + "}"; + + RequestBody requestBody = RequestBody.create(JSON, apiString); Request request = new Request.Builder() .url(updateAPIEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + accessTokenInfo.getAccess_token()) - .post(requestBody) + .put(requestBody) .build(); try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { + if (HttpStatus.SC_OK == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { @@ -388,7 +474,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return updateApi(apiApplicationKey, refreshedAccessToken, api); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid API request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -398,7 +484,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -429,7 +515,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //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"; + String msg = "Bad Request, Invalid API definition request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -439,7 +525,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -450,7 +536,6 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/mediation-policies"; - Request request = new Request.Builder() .url(getAPIMediationEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -471,7 +556,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiIdentifier); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); } else { @@ -481,7 +566,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -513,7 +598,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //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"; + String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); } else { @@ -523,7 +608,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -557,7 +642,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return updateApiSpecificMediationPolicyContent(apiApplicationKey, refreshedAccessToken, uuid, mediation); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid mediation policy"; log.error(msg); throw new BadRequestException(msg); } else { @@ -567,7 +652,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -590,7 +675,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { // Check response status + if (HttpStatus.SC_OK == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -600,7 +685,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //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"; + String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); } else { @@ -610,7 +695,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -641,47 +726,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return getAPIRevisions(apiApplicationKey, refreshedAccessToken, uuid, deploymentStatus); } 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 = endPointPrefix + 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"; + String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); } else { @@ -691,18 +736,18 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override - public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision) + public JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; String apiRevisionDescription = "{\n" + - " \"description\":\" " + apiRevision.getDescription() + "\",\n" + + " \"description\":\"" + apiRevision.getDescription() + "\"\n" + "}"; RequestBody requestBody = RequestBody.create(JSON, apiRevisionDescription); @@ -715,8 +760,9 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return gson.fromJson(response.body().string(), APIRevision.class); + if (HttpStatus.SC_CREATED == 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. @@ -725,7 +771,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return addAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid API revision request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -735,7 +781,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @@ -745,8 +791,17 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException { String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; + APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0); - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeploymentList)); + String revision = "[\n" + + " {\n" + + " \"name\": \"" + apiRevisionDeployment.getDeployment() + "\",\n" + + " \"vhost\": \"" + apiRevisionDeployment.getVhost() + "\",\n" + + " \"displayOnDevportal\": " + apiRevisionDeployment.isDisplayOnDevportal() + "\n" + + " }\n" + + "]"; + + RequestBody requestBody = RequestBody.create(JSON, revision); Request request = new Request.Builder() .url(deployAPIRevisionEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -756,7 +811,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status + if (HttpStatus.SC_CREATED == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -767,7 +822,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { return deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId, apiRevisionDeploymentList); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid API revision request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -777,19 +832,29 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevisionDeployment apiRevisionDeployment, String uuid) + JSONObject apiRevisionDeployment, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" - + apiRevisionDeployment.getRevisionUUID(); + String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId=" + + apiRevisionDeployment.getString("id"); + JSONArray array = apiRevisionDeployment.getJSONArray("deploymentInfo"); + JSONObject obj = array.getJSONObject(0); + + String revision = "[\n" + + " {\n" + + " \"name\": \"" + obj.getString("name") + "\",\n" + + " \"vhost\": \"" + obj.getString("vhost") + "\",\n" + + " \"displayOnDevportal\": " + obj.get("displayOnDevportal") + "\n" + + " }\n" + + "]"; - RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeployment)); + RequestBody requestBody = RequestBody.create(JSON, revision); Request request = new Request.Builder() .url(undeployAPIRevisionEndPoint) .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER @@ -799,7 +864,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status + if (HttpStatus.SC_CREATED == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -809,7 +874,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return undeployAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, apiRevisionDeployment, uuid); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid API revision request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -819,16 +884,17 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) + JSONObject apiRevision, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + apiRevision.getRevisionUUID(); + String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + + apiRevision.getString("id"); Request request = new Request.Builder() .url(apiRevisionEndPoint) @@ -839,7 +905,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { try { Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { // Check response status + if (HttpStatus.SC_OK == response.code()) { return true; } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); @@ -849,7 +915,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return deleteAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision, uuid); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid request"; log.error(msg); throw new BadRequestException(msg); } else { @@ -859,15 +925,15 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override - public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents?limit=1000"; + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000"; Request request = new Request.Builder() .url(getDocumentationsEndPoint) @@ -887,9 +953,9 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return getDocumentations(apiApplicationKey, refreshedAccessToken, apiIdentifier); + return getDocumentations(apiApplicationKey, refreshedAccessToken, uuid); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -899,16 +965,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override public boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier, String documentID) + String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents/" + documentID; + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents/" + documentID; Request request = new Request.Builder() .url(getDocumentationsEndPoint) @@ -927,9 +993,9 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return deleteDocumentations(apiApplicationKey, refreshedAccessToken, apiIdentifier, documentID); + return deleteDocumentations(apiApplicationKey, refreshedAccessToken, uuid, documentID); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -939,16 +1005,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override public Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIIdentifier apiIdentifier, Documentation documentation) + String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/documents"; + String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents"; String document = "{\n" + " \"name\": \" " + documentation.getName() + " \",\n" + @@ -978,9 +1044,9 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); //TODO: max attempt count - return addDocumentation(apiApplicationKey, refreshedAccessToken, apiIdentifier, documentation); + return addDocumentation(apiApplicationKey, refreshedAccessToken, uuid, documentation); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid documentation request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -990,16 +1056,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, e); } } @Override public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - API api, String docId, String docContent) + APIResponseUtil api, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getUuid() + "/documents/" + docId; + String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId() + "/documents/" + docId; RequestBody requestBody = RequestBody.create(JSON, docContent); Request request = new Request.Builder() @@ -1021,7 +1087,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { //TODO: max attempt count return addDocumentationContent(apiApplicationKey, refreshedAccessToken, api, docId, docContent); } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; + String msg = "Bad Request, Invalid documentation request body"; log.error(msg); throw new BadRequestException(msg); } else { @@ -1031,7 +1097,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } catch (IOException e) { String msg = "Error occurred while processing the response"; log.error(msg, e); - throw new APIServicesException(e); + throw new APIServicesException(msg, 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/util/APIUtils/APIResponseUtil.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/APIResponseUtil.java new file mode 100644 index 0000000000..14ac774ebc --- /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/APIResponseUtil.java @@ -0,0 +1,460 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; + +import org.json.JSONObject; +import org.wso2.carbon.apimgt.api.model.APICategory; +import org.wso2.carbon.apimgt.api.model.CORSConfiguration; +import org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * This class represents the API response. + */ + +public class APIResponseUtil { + + private String id; + private String name; + private String description; + private String context; + private String version; + private String provider; + private String lifeCycleStatus; + private String wsdlInfo; + private String wsdlUrl; + private boolean responseCachingEnabled; + private int cacheTimeout; + private boolean hasThumbnail; + private boolean isDefaultVersion; + private boolean isRevision; + private String revisionedApiId; + private int revisionId; + private boolean enableSchemaValidation; + private String type; + private Set transport; + private Set tags; + private Set policies; + private String apiThrottlingPolicy; + private String authorizationHeader; + private String securityScheme; + private String maxTps; + private String visibility; + private String visibleRoles; + private String visibleTenants; + private String mediationPolicies; + private String subscriptionAvailability; + private String subscriptionAvailableTenants; + private String additionalProperties; + private String monetization; + private String accessControl; + private String accessControlRoles; + private BusinessInformation businessInformation; + private CORSConfiguration corsConfiguration; + private WebsubSubscriptionConfiguration websubSubscriptionConfiguration; + private String workflowStatus; + private String createdTime; + private String lastUpdatedTime; + private JSONObject endpointConfig = new JSONObject(); + private String endpointImplementationType; + private List scopes = new ArrayList(); + private List operations; + private String threatProtectionPolicies; + private List apiCategories; + private List keyManagers = new ArrayList(); + private JSONObject serviceInfo = new JSONObject(); + private AdvertiseInfo advertiseInfo; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getLifeCycleStatus() { + return lifeCycleStatus; + } + + public void setLifeCycleStatus(String lifeCycleStatus) { + this.lifeCycleStatus = lifeCycleStatus; + } + + public String getWsdlInfo() { + return wsdlInfo; + } + + public void setWsdlInfo(String wsdlInfo) { + this.wsdlInfo = wsdlInfo; + } + + public String getWsdlUrl() { + return wsdlUrl; + } + + public void setWsdlUrl(String wsdlUrl) { + this.wsdlUrl = wsdlUrl; + } + + public boolean isResponseCachingEnabled() { + return responseCachingEnabled; + } + + public void setResponseCachingEnabled(boolean responseCachingEnabled) { + this.responseCachingEnabled = responseCachingEnabled; + } + + public int getCacheTimeout() { + return cacheTimeout; + } + + public void setCacheTimeout(int cacheTimeout) { + this.cacheTimeout = cacheTimeout; + } + + public boolean isHasThumbnail() { + return hasThumbnail; + } + + public void setHasThumbnail(boolean hasThumbnail) { + this.hasThumbnail = hasThumbnail; + } + + public boolean isDefaultVersion() { + return isDefaultVersion; + } + + public void setDefaultVersion(boolean defaultVersion) { + isDefaultVersion = defaultVersion; + } + + public boolean isRevision() { + return isRevision; + } + + public void setRevision(boolean revision) { + isRevision = revision; + } + + public String getRevisionedApiId() { + return revisionedApiId; + } + + public void setRevisionedApiId(String revisionedApiId) { + this.revisionedApiId = revisionedApiId; + } + + public int getRevisionId() { + return revisionId; + } + + public void setRevisionId(int revisionId) { + this.revisionId = revisionId; + } + + public boolean isEnableSchemaValidation() { + return enableSchemaValidation; + } + + public void setEnableSchemaValidation(boolean enableSchemaValidation) { + this.enableSchemaValidation = enableSchemaValidation; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Set getTransport() { + return transport; + } + + public void setTransport(Set transport) { + this.transport = transport; + } + + public Set getTags() { + return tags; + } + + public void setTags(Set tags) { + this.tags = tags; + } + + public Set getPolicies() { + return policies; + } + + public void setPolicies(Set policies) { + this.policies = policies; + } + + public String getApiThrottlingPolicy() { + return apiThrottlingPolicy; + } + + public void setApiThrottlingPolicy(String apiThrottlingPolicy) { + this.apiThrottlingPolicy = apiThrottlingPolicy; + } + + public String getAuthorizationHeader() { + return authorizationHeader; + } + + public void setAuthorizationHeader(String authorizationHeader) { + this.authorizationHeader = authorizationHeader; + } + + public String getSecurityScheme() { + return securityScheme; + } + + public void setSecurityScheme(String securityScheme) { + this.securityScheme = securityScheme; + } + + public String getMaxTps() { + return maxTps; + } + + public void setMaxTps(String maxTps) { + this.maxTps = maxTps; + } + + public String getVisibility() { + return visibility; + } + + public void setVisibility(String visibility) { + this.visibility = visibility; + } + + public String getVisibleRoles() { + return visibleRoles; + } + + public void setVisibleRoles(String visibleRoles) { + this.visibleRoles = visibleRoles; + } + + public String getVisibleTenants() { + return visibleTenants; + } + + public void setVisibleTenants(String visibleTenants) { + this.visibleTenants = visibleTenants; + } + + public String getMediationPolicies() { + return mediationPolicies; + } + + public void setMediationPolicies(String mediationPolicies) { + this.mediationPolicies = mediationPolicies; + } + + public String getSubscriptionAvailability() { + return subscriptionAvailability; + } + + public void setSubscriptionAvailability(String subscriptionAvailability) { + this.subscriptionAvailability = subscriptionAvailability; + } + + public String getSubscriptionAvailableTenants() { + return subscriptionAvailableTenants; + } + + public void setSubscriptionAvailableTenants(String subscriptionAvailableTenants) { + this.subscriptionAvailableTenants = subscriptionAvailableTenants; + } + + public String getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(String additionalProperties) { + this.additionalProperties = additionalProperties; + } + + public String getMonetization() { + return monetization; + } + + public void setMonetization(String monetization) { + this.monetization = monetization; + } + + public String getAccessControl() { + return accessControl; + } + + public void setAccessControl(String accessControl) { + this.accessControl = accessControl; + } + + public String getAccessControlRoles() { + return accessControlRoles; + } + + public void setAccessControlRoles(String accessControlRoles) { + this.accessControlRoles = accessControlRoles; + } + + public BusinessInformation getBusinessInformation() { + return businessInformation; + } + + public void setBusinessInformation(BusinessInformation businessInformation) { + this.businessInformation = businessInformation; + } + + public CORSConfiguration getCorsConfiguration() { + return corsConfiguration; + } + + public void setCorsConfiguration(CORSConfiguration corsConfiguration) { + this.corsConfiguration = corsConfiguration; + } + + public WebsubSubscriptionConfiguration getWebsubSubscriptionConfiguration() { + return websubSubscriptionConfiguration; + } + + public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfiguration websubSubscriptionConfiguration) { + this.websubSubscriptionConfiguration = websubSubscriptionConfiguration; + } + + public String getWorkflowStatus() { + return workflowStatus; + } + + public void setWorkflowStatus(String workflowStatus) { + this.workflowStatus = workflowStatus; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public String getLastUpdatedTime() { + return lastUpdatedTime; + } + + public void setLastUpdatedTime(String lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + + public JSONObject getEndpointConfig() { + return endpointConfig; + } + + public void setEndpointConfig(JSONObject endpointConfig) { + this.endpointConfig = endpointConfig; + } + + public String getEndpointImplementationType() { + return endpointImplementationType; + } + + public void setEndpointImplementationType(String endpointImplementationType) { + this.endpointImplementationType = endpointImplementationType; + } + + public ListgetScopes() { + return scopes; + } + + public void setScopes(List scopes) { + this.scopes = scopes; + } + + public List getOperations() { + return operations; + } + + public void setOperations(List operations) { + this.operations = operations; + } + + public String getThreatProtectionPolicies() { + return threatProtectionPolicies; + } + + public void setThreatProtectionPolicies(String threatProtectionPolicies) { + this.threatProtectionPolicies = threatProtectionPolicies; + } + + public List getApiCategories() { + return apiCategories; + } + + public void setApiCategories(List apiCategories) { + this.apiCategories = apiCategories; + } + + public List getKeyManagers() { + return keyManagers; + } + + public void setKeyManagers(List keyManagers) { + this.keyManagers = keyManagers; + } + + public JSONObject getServiceInfo() { + return serviceInfo; + } + + public void setServiceInfo(JSONObject serviceInfo) { + this.serviceInfo = serviceInfo; + } + + public AdvertiseInfo getAdvertiseInfo() { + return advertiseInfo; + } + + public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) { + this.advertiseInfo = advertiseInfo; + } +} 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/AdvertiseInfo.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/AdvertiseInfo.java new file mode 100644 index 0000000000..455abe412d --- /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/AdvertiseInfo.java @@ -0,0 +1,41 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; + +public class AdvertiseInfo { + + private boolean advertised; + private String originalDevPortalUrl; + private String apiOwner; + private String vendor; + + public boolean isAdvertised() { + return advertised; + } + + public void setAdvertised(boolean advertised) { + this.advertised = advertised; + } + + public String getOriginalDevPortalUrl() { + return originalDevPortalUrl; + } + + public void setOriginalDevPortalUrl(String originalDevPortalUrl) { + this.originalDevPortalUrl = originalDevPortalUrl; + } + + public String getApiOwner() { + return apiOwner; + } + + public void setApiOwner(String apiOwner) { + this.apiOwner = apiOwner; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } +} 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/BusinessInformation.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/BusinessInformation.java new file mode 100644 index 0000000000..5936616433 --- /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/BusinessInformation.java @@ -0,0 +1,41 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; + +public class BusinessInformation { + + private String businessOwner; + private String businessOwnerEmail; + private String technicalOwner; + private String technicalOwnerEmail; + + public String getBusinessOwner() { + return businessOwner; + } + + public void setBusinessOwner(String businessOwner) { + this.businessOwner = businessOwner; + } + + public String getBusinessOwnerEmail() { + return businessOwnerEmail; + } + + public void setBusinessOwnerEmail(String businessOwnerEmail) { + this.businessOwnerEmail = businessOwnerEmail; + } + + public String getTechnicalOwner() { + return technicalOwner; + } + + public void setTechnicalOwner(String technicalOwner) { + this.technicalOwner = technicalOwner; + } + + public String getTechnicalOwnerEmail() { + return technicalOwnerEmail; + } + + public void setTechnicalOwnerEmail(String technicalOwnerEmail) { + this.technicalOwnerEmail = technicalOwnerEmail; + } +} 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/Operations.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/Operations.java new file mode 100644 index 0000000000..c6e485330a --- /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/Operations.java @@ -0,0 +1,114 @@ +package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; + + +import java.util.Set; + +/** + * This hold the api operations information. + */ + +public class Operations { + + private String id; + private String target; + private String verb; + private String authType; + private String throttlingPolicy; + private Set scopes; + private String usedProductIds; + private String amznResourceName; + private String amznResourceTimeout; + private String payloadSchema; + private String uriMapping; + + public Operations() {} + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public String getVerb() { + return verb; + } + + public void setVerb(String verb) { + this.verb = verb; + } + + public String getAuthType() { + return authType; + } + + public void setAuthType(String authType) { + this.authType = authType; + } + + public String getThrottlingPolicy() { + return throttlingPolicy; + } + + public void setThrottlingPolicy(String throttlingPolicy) { + this.throttlingPolicy = throttlingPolicy; + } + + public Set getScopes() { + return scopes; + } + + public void setScopes(Set scopes) { + this.scopes = scopes; + } + + public String getUsedProductIds() { + return usedProductIds; + } + + public void setUsedProductIds(String usedProductIds) { + this.usedProductIds = usedProductIds; + } + + public String getAmznResourceName() { + return amznResourceName; + } + + public void setAmznResourceName(String amznResourceName) { + this.amznResourceName = amznResourceName; + } + + public String getAmznResourceTimeout() { + return amznResourceTimeout; + } + + public void setAmznResourceTimeout(String amznResourceTimeout) { + this.amznResourceTimeout = amznResourceTimeout; + } + + public String getPayloadSchema() { + return payloadSchema; + } + + public void setPayloadSchema(String payloadSchema) { + this.payloadSchema = payloadSchema; + } + + public String getUriMapping() { + return uriMapping; + } + + public void setUriMapping(String uriMapping) { + this.uriMapping = uriMapping; + } + +} 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/ScopeUtils.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/ScopeUtils.java index a9fa3a3cb9..94b70560c7 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/util/ScopeUtils.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/ScopeUtils.java @@ -27,6 +27,10 @@ public class ScopeUtils { private String name; private String roles; private String description; + private int id; + + public ScopeUtils() { + } public String getKey() { return key; @@ -71,4 +75,4 @@ public class ScopeUtils { "}"; return jsonString; } -} \ No newline at end of file +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 024bf7660e..3610aa4f36 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -177,6 +177,9 @@ io.entgra.device.mgt.core.apimgt.extension.rest.api, io.entgra.device.mgt.core.apimgt.extension.rest.api.dto, io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions, + io.entgra.device.mgt.core.apimgt.extension.rest.api.constants, + io.entgra.device.mgt.core.apimgt.extension.rest.api.util.*, + io.entgra.device.mgt.core.apimgt.annotations, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, 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 9765e14af8..52d3dc5ebc 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 @@ -22,11 +22,13 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationService import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; +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; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,18 +38,14 @@ import org.json.JSONArray; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; -import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIRevision; import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; import org.wso2.carbon.apimgt.api.model.CORSConfiguration; import org.wso2.carbon.apimgt.api.model.Mediation; import org.wso2.carbon.apimgt.api.model.Scope; -import org.wso2.carbon.apimgt.api.model.Tier; -import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; -import org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; @@ -90,6 +88,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { private static final String API_PUBLISH_ENVIRONMENT = "Default"; private static final String CREATED_STATUS = "CREATED"; private static final String PUBLISH_ACTION = "Publish"; + public static final String SUBSCRIPTION_TO_ALL_TENANTS = "ALL_TENANTS"; + public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT"; + public static final String API_GLOBAL_VISIBILITY = "PUBLIC"; + public static final String API_PRIVATE_VISIBILITY = "PRIVATE"; + private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); @Override @@ -156,14 +159,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { 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())){ + if (apiObj.getString("name").equals(apiIdentifier.getApiName().replace(Constants.SPACE, + Constants.EMPTY_STRING))){ apiFound = true; + apiIdentifier.setUuid(apiObj.getString("id")); } } - if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { @@ -177,12 +180,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } - API api = getAPI(apiConfig, true); - api.setId(apiIdentifier); - JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); // add api + APIResponseUtil api = getAPI(apiConfig, true); + JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - api.getUuid(), apiConfig.getAsyncApiDefinition()); + createdAPI.getString("id"), apiConfig.getAsyncApiDefinition()); } if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) { // if endpoint type "dynamic" and then add in sequence @@ -202,7 +204,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiRevision.setApiUUID(createdAPI.getString("id")); apiRevision.setDescription("Initial Revision"); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getRevisionUUID(); + accessTokenInfo, apiRevision).getString("id"); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); @@ -253,12 +255,11 @@ public class APIPublisherServiceImpl implements APIPublisherService { } // Get existing API - API existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier); - + JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes - API api = getAPI(apiConfig, false); - api.setStatus(existingAPI.getStatus()); + APIResponseUtil api = getAPI(apiConfig, false); + api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus")); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { @@ -271,14 +272,15 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier);; - API api = getAPI(apiConfig, true); - api.setStatus(existingAPI.getStatus()); + existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); + APIResponseUtil api = getAPI(apiConfig, true); + api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus")); + api.setId(existingAPI.getString("id")); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - api.getUuid(), apiConfig.getAsyncApiDefinition()); + existingAPI.getString("id"), apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -298,56 +300,61 @@ public class APIPublisherServiceImpl implements APIPublisherService { m.setConfig(apiConfig.getInSequenceConfig()); publisherRESTAPIServices. updateApiSpecificMediationPolicyContent(apiApplicationKey, - accessTokenInfo, existingAPI.getUuid(), m); + accessTokenInfo, existingAPI.getString("id"), m); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, existingAPI.getUuid(), mediation); + accessTokenInfo, existingAPI.getString("id"), mediation); } } - List revisionDeploymentList = (List) - publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid()); + // This will retrieve the deployed revision + JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, + accessTokenInfo, existingAPI.getString("id"), "?query=deployed:true").get("list"); // This will retrieve the un deployed revision list - List undeployedRevisionList = (List) - publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, - existingAPI.getUuid(), "?query=deployed:false").get("list"); - + JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, + existingAPI.getString("id"), "?query=deployed:false").get("list"); int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getUuid(), "").get("count"); + accessTokenInfo, existingAPI.getString("id"), "").get("count"); if (apiRevisionCount >= 5) { - APIRevisionDeployment latestRevisionDeployment = revisionDeploymentList.get(0); - APIRevision earliestUndeployRevision = undeployedRevisionList.get(0); - + JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0); + JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0); publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, - accessTokenInfo, latestRevisionDeployment, existingAPI.getUuid()); - + accessTokenInfo, latestRevisionDeployment, existingAPI.getString("id")); publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, - earliestUndeployRevision, existingAPI.getUuid()); + earliestUndeployRevision, existingAPI.getString("id")); } // create new revision APIRevision apiRevision = new APIRevision(); - apiRevision.setApiUUID(existingAPI.getUuid()); + apiRevision.setApiUUID(existingAPI.getString("id")); apiRevision.setDescription("Updated Revision"); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getRevisionUUID(); + accessTokenInfo, apiRevision).getString("id"); + + APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); + apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); + apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host")); + apiRevisionDeployment.setDisplayOnDevportal(true); + + List apiRevisionDeploymentList = new ArrayList<>(); + apiRevisionDeploymentList.add(apiRevisionDeployment); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - existingAPI.getUuid(), apiRevisionId, revisionDeploymentList); + existingAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); - if (CREATED_STATUS.equals(existingAPI.getStatus())) { + if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) { publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo, - existingAPI.getUuid(), PUBLISH_ACTION); + existingAPI.getString("id"), PUBLISH_ACTION); } } } if (apiConfig.getApiDocumentationSourceFile() != null) { - API api = getAPI(apiConfig, true); + APIResponseUtil api = getAPI(apiConfig, true); String fileName = CarbonUtils.getCarbonHome() + File.separator + "repository" + @@ -531,103 +538,137 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } - private API getAPI(APIConfig config, boolean includeScopes) { - - APIIdentifier apiIdentifier = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion()); - API api = new API(apiIdentifier); - api.setDescription(""); - String context = config.getContext(); - context = context.startsWith("/") ? context : ("/" + context); - api.setContext(context + "/" + config.getVersion()); - api.setStatus(CREATED_STATUS); - api.setWsdlUrl(null); - api.setResponseCache("Disabled"); - api.setContextTemplate(context + "/{version}"); - if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { - api.setAsyncApiDefinition(config.getAsyncApiDefinition()); - AsyncApiParser asyncApiParser = new AsyncApiParser(); - try { - api.setUriTemplates(asyncApiParser.getURITemplates(config.getAsyncApiDefinition(), true)); - } catch (APIManagementException e) { + private APIResponseUtil getAPI(APIConfig config, boolean includeScopes) { + + APIResponseUtil apiResponseUtil = new APIResponseUtil(); + apiResponseUtil.setName(config.getName().replace(Constants.SPACE, Constants.EMPTY_STRING)); + apiResponseUtil.setDescription(""); + apiResponseUtil.setContext(config.getContext()); + apiResponseUtil.setVersion(config.getVersion()); + apiResponseUtil.setProvider(config.getOwner()); + apiResponseUtil.setLifeCycleStatus(CREATED_STATUS); + apiResponseUtil.setWsdlInfo(null); + apiResponseUtil.setWsdlUrl(null); + apiResponseUtil.setResponseCachingEnabled(false); + apiResponseUtil.setCacheTimeout(0); + apiResponseUtil.setHasThumbnail(false); + apiResponseUtil.setDefaultVersion(config.isDefault()); + apiResponseUtil.setRevision(false); + apiResponseUtil.setRevisionedApiId(null); + apiResponseUtil.setEnableSchemaValidation(false); - } - api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition())); + Set tags = new HashSet<>(); + tags.addAll(Arrays.asList(config.getTags())); + apiResponseUtil.setTags(tags); + + Set availableTiers = new HashSet<>(); + if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { + availableTiers.add(WS_UNLIMITED_TIER); } else { - api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config)); + availableTiers.add(UNLIMITED_TIER); + } + apiResponseUtil.setPolicies(availableTiers); - Set uriTemplates = new HashSet<>(); + if (config.getEndpointType() == null) { + List operations = new ArrayList(); + List scopeSet = new ArrayList(); Iterator iterator; for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { ApiUriTemplate apiUriTemplate = iterator.next(); - URITemplate uriTemplate = new URITemplate(); - uriTemplate.setAuthType(apiUriTemplate.getAuthType()); - uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb()); - uriTemplate.setResourceURI(apiUriTemplate.getResourceURI()); - uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate()); + JSONObject operation = new JSONObject(); + operation.put("target", apiUriTemplate.getUriTemplate()); + operation.put("verb", apiUriTemplate.getHttpVerb()); + operation.put("authType", apiUriTemplate.getAuthType()); + operation.put("throttlingPolicy", UNLIMITED_TIER); if (includeScopes) { - Scope scope = new Scope(); if (apiUriTemplate.getScope() != null) { - scope.setName(apiUriTemplate.getScope().getName()); - scope.setDescription(apiUriTemplate.getScope().getDescription()); - scope.setKey(apiUriTemplate.getScope().getKey()); - scope.setRoles(apiUriTemplate.getScope().getRoles()); - uriTemplate.setScopes(scope); + String scopeString = "{\n" + + " \"scope\": {\n" + + " \"id\": null,\n" + + " \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" + + " \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" + + " \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" + + " \"bindings\": [\n" + + " \"" + apiUriTemplate.getScope().getRoles() + "\"\n" + + " ],\n" + + " \"usageCount\": null\n" + + " },\n" + + " \"shared\": true\n" + + " }"; + JSONObject scope = new JSONObject(scopeString); + scopeSet.add(scope); + + Set scopes = new HashSet<>(); + scopes.add(apiUriTemplate.getScope().getKey()); + operation.put("scopes", scopes); } - } - uriTemplates.add(uriTemplate); + operations.add(operation); } - api.setUriTemplates(uriTemplates); + apiResponseUtil.setScopes(scopeSet); + apiResponseUtil.setOperations(operations); } - api.setApiOwner(config.getOwner()); - - - api.setDefaultVersion(config.isDefault()); - - Set tags = new HashSet<>(); - tags.addAll(Arrays.asList(config.getTags())); - api.setTags(tags); - - Set availableTiers = new HashSet<>(); - if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { - availableTiers.add(new Tier(WS_UNLIMITED_TIER)); + if (config.isSharedWithAllTenants()) { + apiResponseUtil.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS); + apiResponseUtil.setVisibility(API_GLOBAL_VISIBILITY); } else { - availableTiers.add(new Tier(UNLIMITED_TIER)); + apiResponseUtil.setSubscriptionAvailability(SUBSCRIPTION_TO_CURRENT_TENANT); + apiResponseUtil.setVisibility(API_PRIVATE_VISIBILITY); } - api.setAvailableTiers(availableTiers); - Set environments = new HashSet<>(); - environments.add(API_PUBLISH_ENVIRONMENT); - api.setEnvironments(environments); + String endpointConfig; + endpointConfig = "{\n" + + " \"endpoint_type\": \"http\",\n" + + " \"sandbox_endpoints\": {\n" + + " \"url\": \"" + config.getEndpoint() + "\"\n" + + " },\n" + + " \"production_endpoints\": {\n" + + " \"url\": \"" + config.getEndpoint() + "\"\n" + + " }\n" + + " }"; + JSONObject endPointConfig = new JSONObject(endpointConfig); - if (config.isSharedWithAllTenants()) { - api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS); - api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); - } else { - api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT); - api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY); - } - String endpointConfig = "{ \"endpoint_type\": \"http\", \"sandbox_endpoints\": { \"url\": \" " + - config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" " + config.getEndpoint() + "\" } }"; - api.setTransports(config.getTransports()); - api.setType("HTTP"); + Set transports = new HashSet<>(); + transports.addAll(Arrays.asList(config.getTransports())); + apiResponseUtil.setTransport(transports); + + apiResponseUtil.setType("HTTP"); - // if dynamic endpoint if (config.getEndpointType() != null && "dynamic".equals(config.getEndpointType())) { - endpointConfig = "{ \"endpoint_type\":\"default\", \"sandbox_endpoints\":{ \"url\":\"default\" }, \"production_endpoints\":{ \"url\":\"default\" } }"; - api.setInSequence(config.getInSequenceName()); + endpointConfig = "{\n" + + " \"endpoint_type\": \"http\",\n" + + " \"sandbox_endpoints\": {\n" + + " \"url\": \" default \"\n" + + " },\n" + + " \"production_endpoints\": {\n" + + " \"url\": \" default \"\n" + + " }\n" + + " }"; + endPointConfig = new JSONObject(endpointConfig); + //TODO: Will be used in dynamic endpoints +// apiResponseUtil.setInSequence(config.getInSequenceName()); } // if ws endpoint if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { - endpointConfig = "{ \"endpoint_type\": \"ws\", \"sandbox_endpoints\": { \"url\": \" " + - config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" " + config.getEndpoint() - + "\" } }"; - api.setTransports("wss,ws"); - api.setType("WS"); + endpointConfig = "{\n" + + " \"endpoint_type\": \"ws\",\n" + + " \"sandbox_endpoints\": {\n" + + " \"url\": \"" + config.getEndpoint() + "\"\n" + + " },\n" + + " \"production_endpoints\": {\n" + + " \"url\": \"" + config.getEndpoint() + "\"\n" + + " }\n" + + " }"; + endPointConfig = new JSONObject(endpointConfig); + + transports.addAll(Arrays.asList("wss,ws")); + apiResponseUtil.setTransport(transports); + apiResponseUtil.setType("WS"); } - api.setEndpointConfig(endpointConfig); + apiResponseUtil.setEndpointConfig(endPointConfig); + List accessControlAllowOrigins = new ArrayList<>(); accessControlAllowOrigins.add("*"); @@ -647,15 +688,53 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessControlAllowMethods.add("OPTIONS"); CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false, accessControlAllowHeaders, accessControlAllowMethods); - api.setCorsConfiguration(corsConfiguration); + apiResponseUtil.setCorsConfiguration(corsConfiguration); - api.setAuthorizationHeader("Authorization"); + apiResponseUtil.setAuthorizationHeader("Authorization"); List keyManagers = new ArrayList<>(); keyManagers.add("all"); - api.setKeyManagers(keyManagers); - api.setEnableStore(true); - api.setEnableSchemaValidation(false); - api.setMonetizationEnabled(false); - return api; + apiResponseUtil.setKeyManagers(keyManagers); + apiResponseUtil.setEnableSchemaValidation(false); + apiResponseUtil.setMonetization(null); + apiResponseUtil.setServiceInfo(null); + + return apiResponseUtil; + + //TODO: Will be used in WS or dynamic endpoints +// if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { +// api.setAsyncApiDefinition(config.getAsyncApiDefinition()); +// AsyncApiParser asyncApiParser = new AsyncApiParser(); +// try { +// api.setUriTemplates(asyncApiParser.getURITemplates(config.getAsyncApiDefinition(), true)); +// } catch (APIManagementException e) { +// +// } +// api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition())); +// } else { +// api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config)); +// +// Set uriTemplates = new HashSet<>(); +// Iterator iterator; +// for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { +// ApiUriTemplate apiUriTemplate = iterator.next(); +// URITemplate uriTemplate = new URITemplate(); +// uriTemplate.setAuthType(apiUriTemplate.getAuthType()); +// uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb()); +// uriTemplate.setResourceURI(apiUriTemplate.getResourceURI()); +// uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate()); +// if (includeScopes) { +// Scope scope = new Scope(); +// if (apiUriTemplate.getScope() != null) { +// scope.setName(apiUriTemplate.getScope().getName()); +// scope.setDescription(apiUriTemplate.getScope().getDescription()); +// scope.setKey(apiUriTemplate.getScope().getKey()); +// scope.setRoles(apiUriTemplate.getScope().getRoles()); +// uriTemplate.setScopes(scope); +// } +// } +// uriTemplates.add(uriTemplate); +// } +// api.setUriTemplates(uriTemplates); +// } } } From 7246209bd826e62bc02d47a17e2fc5fbe1616546 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 25 May 2023 12:55:25 +0530 Subject: [PATCH 08/11] Added licence header for newly added files --- .../api/util/APIUtils/APIResponseUtil.java | 18 +++++++++++++++ .../rest/api/util/APIUtils/AdvertiseInfo.java | 21 ++++++++++++++++++ .../util/APIUtils/BusinessInformation.java | 22 +++++++++++++++++++ .../rest/api/util/APIUtils/Operations.java | 21 +++++++++++++++--- 4 files changed, 79 insertions(+), 3 deletions(-) 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/APIResponseUtil.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/APIResponseUtil.java index 14ac774ebc..cf0d50d465 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/util/APIUtils/APIResponseUtil.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/APIResponseUtil.java @@ -1,3 +1,21 @@ +/* + * 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.APIUtils; import org.json.JSONObject; 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/AdvertiseInfo.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/AdvertiseInfo.java index 455abe412d..4762a260ca 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/util/APIUtils/AdvertiseInfo.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/AdvertiseInfo.java @@ -1,5 +1,26 @@ +/* + * 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.APIUtils; +/** + * This hold the advertisement information of an API. + */ public class AdvertiseInfo { private boolean advertised; 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/BusinessInformation.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/BusinessInformation.java index 5936616433..8a8d351dae 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/util/APIUtils/BusinessInformation.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/BusinessInformation.java @@ -1,5 +1,27 @@ +/* + * 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.APIUtils; + +/** + * This hold the business information of an API. + */ public class BusinessInformation { private String businessOwner; 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/Operations.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/Operations.java index c6e485330a..fae81de88a 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/util/APIUtils/Operations.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/Operations.java @@ -1,14 +1,29 @@ -package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; +/* + * 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.APIUtils; import java.util.Set; /** * This hold the api operations information. */ - public class Operations { - private String id; private String target; private String verb; From b133f569652fd3b0ee307ea6cd893c5025db20e4 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 25 May 2023 13:17:07 +0530 Subject: [PATCH 09/11] Cleanup code base and fix getApiRevision method --- .../pom.xml | 5 ----- .../rest/api/PublisherRESTAPIServices.java | 3 +-- .../rest/api/PublisherRESTAPIServicesImpl.java | 5 +++-- .../api/util/APIUtils/BusinessInformation.java | 1 - .../pom.xml | 1 - .../publisher/APIPublisherServiceImpl.java | 17 ++++++++++------- 6 files changed, 14 insertions(+), 18 deletions(-) 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 4bb277f623..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 @@ -84,11 +84,6 @@ okhttp compile - - org.wso2.orbit.com.fasterxml.jackson.core - jackson-databind - provided - 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 33d124e5fa..35134c6610 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,6 @@ 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; -import org.json.JSONArray; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.Scope; @@ -82,7 +81,7 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String deploymentStatus) + Boolean deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException; JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, 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 bfc2e1661d..dcb9eb6335 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 @@ -701,10 +701,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String deploymentStatus) + Boolean deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions" + deploymentStatus; + String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:" + + deploymentStatus; Request request = new Request.Builder() .url(getAPIRevisionsEndPoint) 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/BusinessInformation.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/BusinessInformation.java index 8a8d351dae..3384100dd6 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/util/APIUtils/BusinessInformation.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/BusinessInformation.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; - /** * This hold the business information of an API. */ diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index 3610aa4f36..c82e0cdfc9 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -179,7 +179,6 @@ io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions, io.entgra.device.mgt.core.apimgt.extension.rest.api.constants, io.entgra.device.mgt.core.apimgt.extension.rest.api.util.*, - io.entgra.device.mgt.core.apimgt.annotations, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, 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 52d3dc5ebc..6c55bf0f26 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 @@ -237,7 +237,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (ApiScope apiScope : apiConfig.getScopes()) { // if the scope is not available as shared scope, and it is assigned to an API as a local scope // need remove the local scope and add as a shared scope - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, + apiScope.getKey())) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { // collect scope to move as shared scopes scopesToMoveAsSharedScopes.add(apiScope); @@ -255,7 +256,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { } // Get existing API - JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); + JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, + apiIdentifier); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes APIResponseUtil api = getAPI(apiConfig, false); @@ -292,7 +294,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setGlobal(false); List mediationList = (List) publisherRESTAPIServices - .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiIdentifier).get("list"); + .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, + apiIdentifier).get("list"); boolean isMediationPolicyFound = false; for (Mediation m : mediationList) { @@ -313,12 +316,12 @@ public class APIPublisherServiceImpl implements APIPublisherService { // This will retrieve the deployed revision JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), "?query=deployed:true").get("list"); + accessTokenInfo, existingAPI.getString("id"), true).get("list"); // This will retrieve the un deployed revision list - JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, accessTokenInfo, - existingAPI.getString("id"), "?query=deployed:false").get("list"); + JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, + accessTokenInfo, existingAPI.getString("id"), false).get("list"); int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, existingAPI.getString("id"), "").get("count"); + accessTokenInfo, existingAPI.getString("id"), null).get("count"); if (apiRevisionCount >= 5) { JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0); From 014f95bd10a7713ce1eec6f721f763bd58f998e9 Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 25 May 2023 13:27:58 +0530 Subject: [PATCH 10/11] Rename API dto file and refactor --- .../rest/api/PublisherRESTAPIServices.java | 8 +- .../api/PublisherRESTAPIServicesImpl.java | 8 +- .../APIInfo/APIInfo.java} | 4 +- .../APIInfo}/AdvertiseInfo.java | 2 +- .../APIInfo}/BusinessInformation.java | 2 +- .../APIUtils => dto/APIInfo}/Operations.java | 2 +- .../pom.xml | 6 +- .../publisher/APIPublisherServiceImpl.java | 88 +++++++++---------- 8 files changed, 58 insertions(+), 62 deletions(-) rename 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/APIResponseUtil.java => dto/APIInfo/APIInfo.java} (99%) rename 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 => dto/APIInfo}/AdvertiseInfo.java (95%) rename 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 => dto/APIInfo}/BusinessInformation.java (95%) rename 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 => dto/APIInfo}/Operations.java (97%) 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 35134c6610..6bc3f17318 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 @@ -23,7 +23,7 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.Scope; @@ -54,10 +54,10 @@ public interface PublisherRESTAPIServices { JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) throws APIServicesException, BadRequestException, UnexpectedResponseException; - JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) + JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) + boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, @@ -113,6 +113,6 @@ public interface PublisherRESTAPIServices { throws APIServicesException, BadRequestException, UnexpectedResponseException; boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIResponseUtil api, String docId, String docContent) + APIInfo api, String docId, String docContent) 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 dcb9eb6335..3308f13115 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 @@ -25,7 +25,7 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.ScopeUtils; import okhttp3.MediaType; @@ -315,7 +315,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) + public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; @@ -402,7 +402,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIResponseUtil api) + public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException { String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); @@ -1063,7 +1063,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { @Override public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIResponseUtil api, String docId, String docContent) + APIInfo api, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId() + "/documents/" + docId; 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/APIResponseUtil.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java similarity index 99% rename from 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/APIResponseUtil.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java index cf0d50d465..a6f76116d9 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/util/APIUtils/APIResponseUtil.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/APIInfo.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; import org.json.JSONObject; import org.wso2.carbon.apimgt.api.model.APICategory; @@ -31,7 +31,7 @@ import java.util.Set; * This class represents the API response. */ -public class APIResponseUtil { +public class APIInfo { private String id; private String name; 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/AdvertiseInfo.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java similarity index 95% rename from 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/AdvertiseInfo.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java index 4762a260ca..93511526aa 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/util/APIUtils/AdvertiseInfo.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/AdvertiseInfo.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; /** * This hold the advertisement information of an API. 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/BusinessInformation.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java similarity index 95% rename from 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/BusinessInformation.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java index 3384100dd6..ad32e51f15 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/util/APIUtils/BusinessInformation.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/BusinessInformation.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; /** * This hold the business information of an API. 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/Operations.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java similarity index 97% rename from 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/Operations.java rename to components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java index fae81de88a..51f2c1ee4c 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/util/APIUtils/Operations.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/dto/APIInfo/Operations.java @@ -16,7 +16,7 @@ * under the License. */ -package io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils; +package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; import java.util.Set; diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml index c82e0cdfc9..e23a764fbb 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/pom.xml @@ -174,11 +174,7 @@ org.scannotation;version="1.0", org.scannotation.archiveiterator;version="1.0", org.w3c.dom, - io.entgra.device.mgt.core.apimgt.extension.rest.api, - io.entgra.device.mgt.core.apimgt.extension.rest.api.dto, - io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions, - io.entgra.device.mgt.core.apimgt.extension.rest.api.constants, - io.entgra.device.mgt.core.apimgt.extension.rest.api.util.*, + io.entgra.device.mgt.core.apimgt.extension.rest.api.*, io.entgra.device.mgt.core.apimgt.annotations, org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api.model, 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 6c55bf0f26..44391fb712 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 @@ -28,7 +28,7 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.APIUtils.APIResponseUtil; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -180,7 +180,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } - APIResponseUtil api = getAPI(apiConfig, true); + APIInfo api = getAPI(apiConfig, true); JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, @@ -260,7 +260,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiIdentifier); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes - APIResponseUtil api = getAPI(apiConfig, false); + APIInfo api = getAPI(apiConfig, false); api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus")); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); @@ -275,7 +275,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); - APIResponseUtil api = getAPI(apiConfig, true); + APIInfo api = getAPI(apiConfig, true); api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus")); api.setId(existingAPI.getString("id")); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); @@ -357,7 +357,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } if (apiConfig.getApiDocumentationSourceFile() != null) { - APIResponseUtil api = getAPI(apiConfig, true); + APIInfo api = getAPI(apiConfig, true); String fileName = CarbonUtils.getCarbonHome() + File.separator + "repository" + @@ -541,28 +541,28 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } - private APIResponseUtil getAPI(APIConfig config, boolean includeScopes) { - - APIResponseUtil apiResponseUtil = new APIResponseUtil(); - apiResponseUtil.setName(config.getName().replace(Constants.SPACE, Constants.EMPTY_STRING)); - apiResponseUtil.setDescription(""); - apiResponseUtil.setContext(config.getContext()); - apiResponseUtil.setVersion(config.getVersion()); - apiResponseUtil.setProvider(config.getOwner()); - apiResponseUtil.setLifeCycleStatus(CREATED_STATUS); - apiResponseUtil.setWsdlInfo(null); - apiResponseUtil.setWsdlUrl(null); - apiResponseUtil.setResponseCachingEnabled(false); - apiResponseUtil.setCacheTimeout(0); - apiResponseUtil.setHasThumbnail(false); - apiResponseUtil.setDefaultVersion(config.isDefault()); - apiResponseUtil.setRevision(false); - apiResponseUtil.setRevisionedApiId(null); - apiResponseUtil.setEnableSchemaValidation(false); + private APIInfo getAPI(APIConfig config, boolean includeScopes) { + + APIInfo apiInfo = new APIInfo(); + apiInfo.setName(config.getName().replace(Constants.SPACE, Constants.EMPTY_STRING)); + apiInfo.setDescription(""); + apiInfo.setContext(config.getContext()); + apiInfo.setVersion(config.getVersion()); + apiInfo.setProvider(config.getOwner()); + apiInfo.setLifeCycleStatus(CREATED_STATUS); + apiInfo.setWsdlInfo(null); + apiInfo.setWsdlUrl(null); + apiInfo.setResponseCachingEnabled(false); + apiInfo.setCacheTimeout(0); + apiInfo.setHasThumbnail(false); + apiInfo.setDefaultVersion(config.isDefault()); + apiInfo.setRevision(false); + apiInfo.setRevisionedApiId(null); + apiInfo.setEnableSchemaValidation(false); Set tags = new HashSet<>(); tags.addAll(Arrays.asList(config.getTags())); - apiResponseUtil.setTags(tags); + apiInfo.setTags(tags); Set availableTiers = new HashSet<>(); if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { @@ -570,7 +570,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } else { availableTiers.add(UNLIMITED_TIER); } - apiResponseUtil.setPolicies(availableTiers); + apiInfo.setPolicies(availableTiers); if (config.getEndpointType() == null) { List operations = new ArrayList(); @@ -608,16 +608,16 @@ public class APIPublisherServiceImpl implements APIPublisherService { } operations.add(operation); } - apiResponseUtil.setScopes(scopeSet); - apiResponseUtil.setOperations(operations); + apiInfo.setScopes(scopeSet); + apiInfo.setOperations(operations); } if (config.isSharedWithAllTenants()) { - apiResponseUtil.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS); - apiResponseUtil.setVisibility(API_GLOBAL_VISIBILITY); + apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS); + apiInfo.setVisibility(API_GLOBAL_VISIBILITY); } else { - apiResponseUtil.setSubscriptionAvailability(SUBSCRIPTION_TO_CURRENT_TENANT); - apiResponseUtil.setVisibility(API_PRIVATE_VISIBILITY); + apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_CURRENT_TENANT); + apiInfo.setVisibility(API_PRIVATE_VISIBILITY); } String endpointConfig; @@ -634,9 +634,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { Set transports = new HashSet<>(); transports.addAll(Arrays.asList(config.getTransports())); - apiResponseUtil.setTransport(transports); + apiInfo.setTransport(transports); - apiResponseUtil.setType("HTTP"); + apiInfo.setType("HTTP"); if (config.getEndpointType() != null && "dynamic".equals(config.getEndpointType())) { endpointConfig = "{\n" + @@ -650,7 +650,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { " }"; endPointConfig = new JSONObject(endpointConfig); //TODO: Will be used in dynamic endpoints -// apiResponseUtil.setInSequence(config.getInSequenceName()); +// apiInfo.setInSequence(config.getInSequenceName()); } // if ws endpoint @@ -667,10 +667,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { endPointConfig = new JSONObject(endpointConfig); transports.addAll(Arrays.asList("wss,ws")); - apiResponseUtil.setTransport(transports); - apiResponseUtil.setType("WS"); + apiInfo.setTransport(transports); + apiInfo.setType("WS"); } - apiResponseUtil.setEndpointConfig(endPointConfig); + apiInfo.setEndpointConfig(endPointConfig); List accessControlAllowOrigins = new ArrayList<>(); accessControlAllowOrigins.add("*"); @@ -691,17 +691,17 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessControlAllowMethods.add("OPTIONS"); CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false, accessControlAllowHeaders, accessControlAllowMethods); - apiResponseUtil.setCorsConfiguration(corsConfiguration); + apiInfo.setCorsConfiguration(corsConfiguration); - apiResponseUtil.setAuthorizationHeader("Authorization"); + apiInfo.setAuthorizationHeader("Authorization"); List keyManagers = new ArrayList<>(); keyManagers.add("all"); - apiResponseUtil.setKeyManagers(keyManagers); - apiResponseUtil.setEnableSchemaValidation(false); - apiResponseUtil.setMonetization(null); - apiResponseUtil.setServiceInfo(null); + apiInfo.setKeyManagers(keyManagers); + apiInfo.setEnableSchemaValidation(false); + apiInfo.setMonetization(null); + apiInfo.setServiceInfo(null); - return apiResponseUtil; + return apiInfo; //TODO: Will be used in WS or dynamic endpoints // if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { From c5a7902386da8b89f3d3389e0b6b779888e8d1df Mon Sep 17 00:00:00 2001 From: pasindu Date: Thu, 25 May 2023 16:50:43 +0530 Subject: [PATCH 11/11] Fix error message and minor fixes in loop and if condition --- .../apimgt/webapp/publisher/APIPublisherServiceImpl.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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 44391fb712..5b0f094a4c 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 @@ -111,7 +111,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { - String errorMsg = "Error while generating application"; + String errorMsg = "Error occurred while generating the API application"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); } @@ -165,6 +165,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { Constants.EMPTY_STRING))){ apiFound = true; apiIdentifier.setUuid(apiObj.getString("id")); + break; } } if (!apiFound) { @@ -387,7 +388,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey, accessTokenInfo, api.getId()).get("list"); - if (!(documentList.length() == 0)) { + if (documentList.length() > 0) { for (int i = 0; i < documentList.length(); i++) { JSONObject existingDoc = documentList.getJSONObject(i); if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName()) @@ -438,7 +439,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); } catch (APIServicesException e) { - String errorMsg = "Error while generating application"; + String errorMsg = "Error occurred while generating the API application"; log.error(errorMsg, e); throw new APIManagerPublisherException(e); }