From a683bd7110c8db80d7294a37719e5bec6b84a1ac Mon Sep 17 00:00:00 2001 From: pasindu Date: Wed, 17 May 2023 10:18:52 +0530 Subject: [PATCH] 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); +// } } }