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 d5f559ff348..7dd0c749146 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 2ea0a51f344..6bc3f17318d 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,16 @@ 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.dto.APIInfo.APIInfo; import org.json.JSONObject; +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; public interface PublisherRESTAPIServices { @@ -34,6 +42,77 @@ 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; + + 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, APIInfo api) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo 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 getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + Boolean deploymentStatus) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject 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, + JSONObject apiRevisionDeployment, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + JSONObject apiRevision, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String documentID) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Documentation documentation) + throws APIServicesException, BadRequestException, UnexpectedResponseException; + + boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + 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 819b91210d4..3308f13115f 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,12 +18,14 @@ 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; 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.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; @@ -35,24 +37,33 @@ 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.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; 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); + 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 @@ -83,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); } } @@ -93,8 +104,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; + String getScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + keyValue; Request request = new Request.Builder() .url(getScopeUrl) @@ -117,6 +127,10 @@ 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.info(msg); + return false; } else { String msg = "Response : " + response.code() + response.body(); throw new UnexpectedResponseException(msg); @@ -124,7 +138,54 @@ 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 addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; + + 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(addNewSharedScopeEndPoint) + .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 addNewSharedScope(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.message(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); } } @@ -132,8 +193,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.GET_SCOPE + scope.getId(); + String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); ScopeUtils scopeUtil = new ScopeUtils(); scopeUtil.setKey(scope.getKey()); @@ -172,7 +232,874 @@ 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 getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiIdentifier.getUUID(); + Request request = new Request.Builder() + .url(getAllApi) + .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 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(msg, e); + } + } + + @Override + public JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAllApis = endPointPrefix + 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(msg, e); + } + } + + @Override + public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; + + 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(addAPIEndPoint) + .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()) { + 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 addAPI(apiApplicationKey, refreshedAccessToken, api); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid API request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response status : " + response.code() + " Response message : " + response.message(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); + + 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()) + .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 updateApi(apiApplicationKey, refreshedAccessToken, api); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid API request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String asyncApiDefinition) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = endPointPrefix + 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()) { //Check the response + 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 API definition request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + + } + + @Override + public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIIdentifier apiIdentifier) + 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 + + 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 request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); } } + + @Override + public boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + 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(addAPIMediation) + .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()) { // Check response status + 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 request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + + } + + + @Override + public boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Mediation mediation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + 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(updateApiMediationEndPOint) + .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()) { // Check response status + 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 updateApiSpecificMediationPolicyContent(apiApplicationKey, refreshedAccessToken, uuid, mediation); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid mediation policy"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + + } + + @Override + public boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String action) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + 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(changeAPIStatusEndPoint) + .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 request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + Boolean deploymentStatus) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:" + + deploymentStatus; + + Request request = new Request.Builder() + .url(getAPIRevisionsEndPoint) + .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 getAPIRevisions(apiApplicationKey, refreshedAccessToken, uuid, deploymentStatus); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public 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" + + "}"; + + 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_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. + 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 API revision request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, + String apiRevisionId, List apiRevisionDeploymentList) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; + APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0); + + 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 + + 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 deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId, + apiRevisionDeploymentList); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid API revision request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + JSONObject apiRevisionDeployment, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + 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, revision); + Request request = new Request.Builder() + .url(undeployAPIRevisionEndPoint) + .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 API revision request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + JSONObject apiRevision, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + + apiRevision.getString("id"); + + 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 request"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/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, uuid); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, String documentID) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/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, uuid, documentID); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + String uuid, Documentation documentation) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/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()) { // Check response status + 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, uuid, documentation); + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = "Bad Request, Invalid documentation request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + + @Override + public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, + APIInfo api, String docId, String docContent) + throws APIServicesException, BadRequestException, UnexpectedResponseException { + + String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId() + "/documents/" + docId; + + RequestBody requestBody = RequestBody.create(JSON, docContent); + Request request = new Request.Builder() + .url(addDocumentationContentEndPoint) + .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()) { // Check response status + 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 documentation request body"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = "Response : " + response.code() + response.body(); + throw new UnexpectedResponseException(msg); + } + } catch (IOException e) { + String msg = "Error occurred while processing the response"; + log.error(msg, e); + throw new APIServicesException(msg, e); + } + } + } 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 e4dd49b3818..30074c7b4ab 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,10 +58,13 @@ 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"; - 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/dto/APIInfo/APIInfo.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 new file mode 100644 index 00000000000..a6f76116d9a --- /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/dto/APIInfo/APIInfo.java @@ -0,0 +1,478 @@ +/* + * 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.dto.APIInfo; + +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 APIInfo { + + 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/dto/APIInfo/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 new file mode 100644 index 00000000000..93511526aae --- /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/dto/APIInfo/AdvertiseInfo.java @@ -0,0 +1,62 @@ +/* + * 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.dto.APIInfo; + +/** + * This hold the advertisement information of an API. + */ +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/dto/APIInfo/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 new file mode 100644 index 00000000000..ad32e51f153 --- /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/dto/APIInfo/BusinessInformation.java @@ -0,0 +1,62 @@ +/* + * 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.dto.APIInfo; + +/** + * This hold the business information of an API. + */ +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/dto/APIInfo/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 new file mode 100644 index 00000000000..51f2c1ee4c0 --- /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/dto/APIInfo/Operations.java @@ -0,0 +1,129 @@ +/* + * 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.dto.APIInfo; + +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 18944c945c6..94b70560c7d 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; @@ -62,13 +66,13 @@ 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; } -} \ 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 024bf7660e7..e23a764fbba 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,9 +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.*, 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 52b81fd5571..5b0f094a4c3 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.dto.APIInfo.APIInfo; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,19 +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.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; 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; @@ -91,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 @@ -100,6 +102,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 occurred while generating the API application"; + log.error(errorMsg, e); + throw new APIManagerPublisherException(e); + } + try { boolean tenantFound = false; boolean tenantsLoaded = false; @@ -140,27 +156,38 @@ 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().replace(Constants.SPACE, + Constants.EMPTY_STRING))){ + apiFound = true; + apiIdentifier.setUuid(apiObj.getString("id")); + break; + } + } + if (!apiFound) { // add new scopes as shared scopes - Set allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); 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); + publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); } } - API api = getAPI(apiConfig, true); - api.setId(apiIdentifier); - API createdAPI = apiProvider.addAPI(api); + APIInfo api = getAPI(apiConfig, true); + JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, + createdAPI.getString("id"), 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(); @@ -168,14 +195,17 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setType("in"); mediation.setGlobal(false); - apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation, - tenantDomain); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, createdAPI.getString("id"), mediation); } - apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); + 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 = apiProvider.addAPIRevision(apiRevision, tenantDomain); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, + accessTokenInfo, apiRevision).getString("id"); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); @@ -184,7 +214,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, + createdAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { @@ -203,12 +234,12 @@ 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 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 (!allSharedScopeKeys.contains(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); @@ -219,19 +250,20 @@ 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); + } } } // Get existing API - API existingAPI = apiProvider.getAPI(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()); - apiProvider.updateAPI(api); + APIInfo api = getAPI(apiConfig, false); + api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus")); + publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { Scope scope = new Scope(); @@ -239,17 +271,19 @@ 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); - API api = getAPI(apiConfig, true); - api.setStatus(existingAPI.getStatus()); - apiProvider.updateAPI(api); + existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier); + APIInfo 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())) { - apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, + existingAPI.getString("id"), apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -260,54 +294,71 @@ 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"); + boolean isMediationPolicyFound = false; 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.getString("id"), m); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { - apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation, - tenantDomain); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, + accessTokenInfo, existingAPI.getString("id"), mediation); } } - // Assumption: Assume the latest revision is the published one - String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); - List latestRevisionDeploymentList = - apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); - - List apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); - if (apiRevisionList.size() >= 5) { - String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); - List earliestRevisionDeploymentList = - apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); - apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList); - apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); + // This will retrieve the deployed revision + JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, + 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"), false).get("list"); + int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, + accessTokenInfo, existingAPI.getString("id"), null).get("count"); + + if (apiRevisionCount >= 5) { + JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0); + JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0); + publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, + accessTokenInfo, latestRevisionDeployment, existingAPI.getString("id")); + publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, + 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 = apiProvider.addAPIRevision(apiRevision, tenantDomain); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, + accessTokenInfo, apiRevision).getString("id"); - apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, latestRevisionDeploymentList); + 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); - if (CREATED_STATUS.equals(existingAPI.getStatus())) { - apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); + publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, + existingAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList); + + if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) { + publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo, + existingAPI.getString("id"), PUBLISH_ACTION); } } } if (apiConfig.getApiDocumentationSourceFile() != null) { - API api = getAPI(apiConfig, true); + APIInfo api = getAPI(apiConfig, true); String fileName = CarbonUtils.getCarbonHome() + File.separator + "repository" + @@ -334,17 +385,29 @@ 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) { + 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)) { + 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); + Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, + api.getId(), apiDocumentation); + + publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, api, + createdDoc.getId(), docContent); } - } catch (FaultGatewaysException | APIManagementException | IOException e) { + } catch (APIManagementException | IOException | APIServicesException | + BadRequestException | UnexpectedResponseException e) { String msg = "Error occurred while publishing api"; log.error(msg, e); throw new APIManagerPublisherException(e); @@ -376,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); } @@ -479,103 +542,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 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); - } - api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition())); + Set tags = new HashSet<>(); + tags.addAll(Arrays.asList(config.getTags())); + apiInfo.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); + } + apiInfo.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); + apiInfo.setScopes(scopeSet); + apiInfo.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()) { + apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS); + apiInfo.setVisibility(API_GLOBAL_VISIBILITY); } else { - availableTiers.add(new Tier(UNLIMITED_TIER)); + apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_CURRENT_TENANT); + apiInfo.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())); + apiInfo.setTransport(transports); + + apiInfo.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 +// apiInfo.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")); + apiInfo.setTransport(transports); + apiInfo.setType("WS"); } - api.setEndpointConfig(endpointConfig); + apiInfo.setEndpointConfig(endPointConfig); + List accessControlAllowOrigins = new ArrayList<>(); accessControlAllowOrigins.add("*"); @@ -595,15 +692,53 @@ public class APIPublisherServiceImpl implements APIPublisherService { accessControlAllowMethods.add("OPTIONS"); CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false, accessControlAllowHeaders, accessControlAllowMethods); - api.setCorsConfiguration(corsConfiguration); + apiInfo.setCorsConfiguration(corsConfiguration); - api.setAuthorizationHeader("Authorization"); + apiInfo.setAuthorizationHeader("Authorization"); List keyManagers = new ArrayList<>(); keyManagers.add("all"); - api.setKeyManagers(keyManagers); - api.setEnableStore(true); - api.setEnableSchemaValidation(false); - api.setMonetizationEnabled(false); - return api; + apiInfo.setKeyManagers(keyManagers); + apiInfo.setEnableSchemaValidation(false); + apiInfo.setMonetization(null); + apiInfo.setServiceInfo(null); + + return apiInfo; + + //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); +// } } }