Fixes in API publishing flow

revert
commit 8385c0c836

@ -19,23 +19,18 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api; package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.List; import java.util.List;
public interface PublisherRESTAPIServices { public interface PublisherRESTAPIServices {
JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key)
@ -47,13 +42,13 @@ public interface PublisherRESTAPIServices {
boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
@ -63,7 +58,7 @@ public interface PublisherRESTAPIServices {
String asyncApiDefinition) String asyncApiDefinition)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String apiUuid) String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -79,11 +74,11 @@ public interface PublisherRESTAPIServices {
String uuid, String action) String uuid, String action)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
Boolean deploymentStatus) Boolean deploymentStatus)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevision) APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -91,15 +86,15 @@ public interface PublisherRESTAPIServices {
String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList) String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
abstract boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevisionDeployment, String uuid) APIRevision apiRevisionDeployment, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevision, String uuid) APIRevision apiRevision, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid) String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
@ -107,7 +102,7 @@ public interface PublisherRESTAPIServices {
String uuid, String documentID) String uuid, String documentID)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Documentation documentation) String uuid, Documentation documentation)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;

@ -21,18 +21,12 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import com.google.gson.Gson; 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.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.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; 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.*; import okhttp3.*;
import okhttp3.Request.Builder; import okhttp3.Request.Builder;
import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpStatus;
@ -56,7 +50,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
+ Constants.COLON + port; + Constants.COLON + port;
@Override @Override
public JSONObject getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) public Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES; String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES;
@ -70,8 +64,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray scopeList = (JSONArray) new JSONObject(response.body().string()).get("list");
return jsonObject; return gson.fromJson(scopeList.toString(), Scope[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -124,7 +118,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} else if (HttpStatus.SC_NOT_FOUND == response.code()) { } else if (HttpStatus.SC_NOT_FOUND == response.code()) {
String msg = "Shared scope key not found"; String msg = "Shared scope key not found : " + key;
log.info(msg); log.info(msg);
return false; return false;
} else { } else {
@ -144,14 +138,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT;
ScopeUtils scopeUtil = new ScopeUtils(); JSONArray bindings = new JSONArray();
scopeUtil.setKey(scope.getKey()); if (scope.getBindings() != null) {
scopeUtil.setName(scope.getName()); for (String str : scope.getBindings()) {
scopeUtil.setDescription(scope.getDescription()); bindings.put(str);
scopeUtil.setRoles(scope.getRoles()); }
String scopeString = scopeUtil.toJSON(); }
RequestBody requestBody = RequestBody.create(JSON, scopeString); JSONObject payload = new JSONObject();
payload.put("name", (scope.getName() != null ? scope.getName() : ""));
payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : ""));
payload.put("description", (scope.getDescription() != null ? scope.getDescription() : ""));
payload.put("bindings", (bindings != null ? bindings : ""));
payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(addNewSharedScopeEndPoint) .url(addNewSharedScopeEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -191,14 +192,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId();
ScopeUtils scopeUtil = new ScopeUtils(); JSONArray bindings = new JSONArray();
scopeUtil.setKey(scope.getKey()); if (scope.getBindings() != null) {
scopeUtil.setName(scope.getName()); for (String str : scope.getBindings()) {
scopeUtil.setDescription(scope.getDescription()); bindings.put(str);
scopeUtil.setRoles(scope.getRoles()); }
String scopeString = scopeUtil.toJSON(); }
JSONObject payload = new JSONObject();
payload.put("name", (scope.getName() != null ? scope.getName() : ""));
payload.put("displayName", (scope.getDisplayName() != null ? scope.getDisplayName() : ""));
payload.put("description", (scope.getDescription() != null ? scope.getDescription() : ""));
payload.put("bindings", (bindings != null ? bindings : ""));
payload.put("usageCount", (scope.getUsageCount() != 0 ? scope.getUsageCount() : 0));
RequestBody requestBody = RequestBody.create(JSON, scopeString); RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(updateScopeUrl) .url(updateScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -233,7 +241,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) public APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid; String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid;
@ -247,8 +255,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); return gson.fromJson(response.body().string(), APIInfo.class);
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -272,7 +279,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) public APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApis = endPointPrefix + Constants.GET_ALL_APIS; String getAllApis = endPointPrefix + Constants.GET_ALL_APIS;
@ -286,8 +293,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list");
return jsonObject; return gson.fromJson(apiList.toString(), APIInfo[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -311,59 +318,111 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) public APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT;
String apiString = "{\n" + JSONObject payload = new JSONObject();
" \"name\": \"" + api.getName() + "\",\n" + payload.put("name", api.getName());
" \"description\":\"" + api.getDescription() + "\",\n" + payload.put("description", api.getDescription());
" \"context\":\"" + api.getContext() + "\",\n" + payload.put("context", api.getContext());
" \"version\":\"" + api.getVersion() + "\",\n" + payload.put("version", api.getVersion());
" \"provider\":\"" + api.getProvider() + "\",\n" + payload.put("provider", api.getProvider());
" \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" + payload.put("lifeCycleStatus", api.getLifeCycleStatus());
" \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" + payload.put("wsdlInfo", (api.getWsdlInfo() != null ? api.getWsdlInfo() : null));
" \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" + payload.put("wsdlUrl", (api.getWsdlUrl() != null ? api.getWsdlUrl() : null));
" \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" + payload.put("responseCachingEnabled", api.isResponseCachingEnabled());
" \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" + payload.put("cacheTimeout", api.getCacheTimeout());
" \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" + payload.put("hasThumbnail", api.isHasThumbnail());
" \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" + payload.put("isDefaultVersion", api.isDefaultVersion());
" \"isRevision\": " + api.isRevision() + ",\n" + payload.put("isRevision", api.isRevision());
" \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" + payload.put("revisionedApiId", (api.getRevisionedApiId() != null ? api.getRevisionedApiId() : null));
" \"revisionId\": " + api.getRevisionId() + ",\n" + payload.put("revisionId", api.getRevisionId());
" \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" + payload.put("enableSchemaValidation", api.isEnableSchemaValidation());
" \"type\": \"" + api.getType() + "\",\n" + payload.put("type", api.getType());
" \"transport\": " + gson.toJson(api.getTransport()) + ",\n" + payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy());
" \"tags\": " + gson.toJson(api.getTags()) + ",\n" + payload.put("authorizationHeader", api.getAuthorizationHeader());
" \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" + payload.put("visibility", api.getVisibility());
" \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : ""));
" \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" +
" \"visibility\": \"" + api.getVisibility() + "\",\n" + //Lists
" \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" + if (api.getTransport() != null) {
" \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + JSONArray transport = new JSONArray();
" \"subscriptionAvailableTenants\": [],\n" + for (String str : api.getTransport()) {
" \"additionalProperties\": [],\n" + transport.put(str);
" \"monetization\": " + api.getMonetization() + ",\n" + }
" \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" + payload.put("transport", transport);
" \"websubSubscriptionConfiguration\": {\n" + }
" \"enable\": false,\n" + if (api.getTags() != null) {
" \"secret\": \"\",\n" + JSONArray tags = new JSONArray();
" \"signingAlgorithm\": \"SHA1\",\n" + for (String str : api.getTags()) {
" \"signatureHeader\": \"x-hub-signature\"\n" + tags.put(str);
" },\n" + }
" \"workflowStatus\": null,\n" + payload.put("tags", tags);
" \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + }
" \"endpointImplementationType\": \"ENDPOINT\",\n" + if (api.getPolicies() != null) {
" \"scopes\": " + api.getScopes().toString() + ",\n" + JSONArray policies = new JSONArray();
" \"operations\": " + (api.getOperations() != null ? api.getOperations().toString() : null) + ",\n" + for (String str : api.getPolicies()) {
" \"threatProtectionPolicies\": null,\n" + policies.put(str);
" \"categories\": [],\n" + }
" \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + payload.put("policies", policies);
" \"serviceInfo\": " + api.getServiceInfo() + "\n" + }
"}"; if (api.getMediationPolicies() != null) {
JSONArray mediationPolicies = new JSONArray();
RequestBody requestBody = RequestBody.create(JSON, apiString); for (MediationPolicy object : api.getMediationPolicies()) {
mediationPolicies.put(new JSONObject(gson.toJson(object)));
}
payload.put("mediationPolicies", mediationPolicies);
}
if (api.getSubscriptionAvailableTenants() != null) {
JSONArray subscriptionAvailableTenants = new JSONArray();
for (String str : api.getSubscriptionAvailableTenants()) {
subscriptionAvailableTenants.put(str);
}
payload.put("subscriptionAvailableTenants", subscriptionAvailableTenants);
}
if (api.getAdditionalProperties() != null) {
JSONArray additionalProperties = new JSONArray();
for (AdditionalProperties str : api.getAdditionalProperties()) {
additionalProperties.put(str);
}
payload.put("additionalProperties", additionalProperties);
}
if (api.getScopes() != null) {
JSONArray scopes = new JSONArray();
for (JSONObject object : api.getScopes()) {
scopes.put(object);
}
payload.put("scopes", scopes);
}
if (api.getOperations() != null) {
JSONArray operations = new JSONArray();
for (Operations operation : api.getOperations()) {
operations.put(new JSONObject(gson.toJson(operation)));
}
payload.put("operations", operations);
}
if (api.getCategories() != null) {
JSONArray categories = new JSONArray();
for (String str : api.getCategories()) {
categories.put(str);
}
payload.put("categories", categories);
}
//objects
payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null));
payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null));
payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null));
payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null));
payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null));
payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null));
payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null));
payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null));
payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(addAPIEndPoint) .url(addAPIEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -374,8 +433,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) { if (HttpStatus.SC_CREATED == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); return gson.fromJson(response.body().string(), APIInfo.class);
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -404,54 +462,106 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId();
String apiString = "{\n" + JSONObject payload = new JSONObject();
" \"name\": \"" + api.getName() + "\",\n" + payload.put("name", api.getName());
" \"description\":\"" + api.getDescription() + "\",\n" + payload.put("description", api.getDescription());
" \"context\":\"" + api.getContext() + "\",\n" + payload.put("context", api.getContext());
" \"version\":\"" + api.getVersion() + "\",\n" + payload.put("version", api.getVersion());
" \"provider\":\"" + api.getProvider() + "\",\n" + payload.put("provider", api.getProvider());
" \"lifeCycleStatus\":\"" + api.getLifeCycleStatus() + "\",\n" + payload.put("lifeCycleStatus", api.getLifeCycleStatus());
" \"wsdlInfo\": " + api.getWsdlInfo() + ",\n" + payload.put("wsdlInfo", (api.getWsdlInfo() != null ? api.getWsdlInfo() : null));
" \"wsdlUrl\":" + api.getWsdlUrl() + ",\n" + payload.put("wsdlUrl", (api.getWsdlUrl() != null ? api.getWsdlUrl() : null));
" \"responseCachingEnabled\": " + api.isResponseCachingEnabled() + ",\n" + payload.put("responseCachingEnabled", api.isResponseCachingEnabled());
" \"cacheTimeout\": " + api.getCacheTimeout() + ",\n" + payload.put("cacheTimeout", api.getCacheTimeout());
" \"hasThumbnail\": " + api.isHasThumbnail() + ",\n" + payload.put("hasThumbnail", api.isHasThumbnail());
" \"isDefaultVersion\": " + api.isDefaultVersion() + ",\n" + payload.put("isDefaultVersion", api.isDefaultVersion());
" \"isRevision\": " + api.isRevision() + ",\n" + payload.put("isRevision", api.isRevision());
" \"revisionedApiId\": " + api.getRevisionedApiId() + ",\n" + payload.put("revisionedApiId", (api.getRevisionedApiId() != null ? api.getRevisionedApiId() : null));
" \"revisionId\": " + api.getRevisionId() + ",\n" + payload.put("revisionId", api.getRevisionId());
" \"enableSchemaValidation\": " + api.isEnableSchemaValidation() + ",\n" + payload.put("enableSchemaValidation", api.isEnableSchemaValidation());
" \"type\": \"" + api.getType() + "\",\n" + payload.put("type", api.getType());
" \"transport\": " + gson.toJson(api.getTransport()) + ",\n" + payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy());
" \"tags\": " + gson.toJson(api.getTags()) + ",\n" + payload.put("authorizationHeader", api.getAuthorizationHeader());
" \"policies\": " + gson.toJson(api.getPolicies()) + ",\n" + payload.put("visibility", api.getVisibility());
" \"apiThrottlingPolicy\": " + api.getApiThrottlingPolicy() + ",\n" + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : ""));
" \"authorizationHeader\": \"" + api.getAuthorizationHeader() + "\",\n" +
" \"visibility\": \"" + api.getVisibility() + "\",\n" + //Lists
" \"mediationPolicies\": " + (api.getInSequence() != null ? "[{\"name\": \"" + api.getInSequence() + "\",\"type\": \"in\"}]" : null) + ",\n" + if (api.getTransport() != null) {
" \"subscriptionAvailability\": \"" + api.getSubscriptionAvailability() + "\",\n" + JSONArray transport = new JSONArray();
" \"subscriptionAvailableTenants\": [],\n" + for (String str : api.getTransport()) {
" \"additionalProperties\": [],\n" + transport.put(str);
" \"monetization\": " + api.getMonetization() + ",\n" + }
" \"corsConfiguration\": " + gson.toJson(api.getCorsConfiguration()) + ",\n" + payload.put("transport", transport);
" \"websubSubscriptionConfiguration\": {\n" + }
" \"enable\": false,\n" + if (api.getTags() != null) {
" \"secret\": \"\",\n" + JSONArray tags = new JSONArray();
" \"signingAlgorithm\": \"SHA1\",\n" + for (String str : api.getTags()) {
" \"signatureHeader\": \"x-hub-signature\"\n" + tags.put(str);
" },\n" + }
" \"workflowStatus\": null,\n" + payload.put("tags", tags);
" \"endpointConfig\": " + api.getEndpointConfig().toString() + ",\n" + }
" \"endpointImplementationType\": \"ENDPOINT\",\n" + if (api.getPolicies() != null) {
" \"scopes\": " + api.getScopes().toString() + ",\n" + JSONArray policies = new JSONArray();
" \"operations\": " + (api.getOperations() != null? api.getOperations().toString() : null) + ",\n" + for (String str : api.getPolicies()) {
" \"threatProtectionPolicies\": null,\n" + policies.put(str);
" \"categories\": [],\n" + }
" \"keyManagers\": " + gson.toJson(api.getKeyManagers()) + ",\n" + payload.put("policies", policies);
" \"serviceInfo\": " + api.getServiceInfo() + "\n" + }
"}"; if (api.getMediationPolicies() != null) {
JSONArray mediationPolicies = new JSONArray();
RequestBody requestBody = RequestBody.create(JSON, apiString); for (MediationPolicy object : api.getMediationPolicies()) {
mediationPolicies.put(new JSONObject(gson.toJson(object)));
}
payload.put("mediationPolicies", mediationPolicies);
}
if (api.getSubscriptionAvailableTenants() != null) {
JSONArray subscriptionAvailableTenants = new JSONArray();
for (String str : api.getSubscriptionAvailableTenants()) {
subscriptionAvailableTenants.put(str);
}
payload.put("subscriptionAvailableTenants", subscriptionAvailableTenants);
}
if (api.getAdditionalProperties() != null) {
JSONArray additionalProperties = new JSONArray();
for (AdditionalProperties str : api.getAdditionalProperties()) {
additionalProperties.put(str);
}
payload.put("additionalProperties", additionalProperties);
}
if (api.getScopes() != null) {
JSONArray scopes = new JSONArray();
for (JSONObject object : api.getScopes()) {
scopes.put(object);
}
payload.put("scopes", scopes);
}
if (api.getOperations() != null) {
JSONArray operations = new JSONArray();
for (Operations operation : api.getOperations()) {
operations.put(new JSONObject(gson.toJson(operation)));
}
payload.put("operations", operations);
}
if (api.getCategories() != null) {
JSONArray categories = new JSONArray();
for (String str : api.getCategories()) {
categories.put(str);
}
payload.put("categories", categories);
}
//objects
payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null));
payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null));
payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null));
payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null));
payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null));
payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null));
payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null));
payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null));
payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null));
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(updateAPIEndPoint) .url(updateAPIEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -463,7 +573,6 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
return true; return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -534,7 +643,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, public MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String apiUuid) String apiUuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
@ -549,8 +658,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.body().string()).get("list");
return jsonObject; return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -705,7 +814,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, public APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
Boolean deploymentStatus) Boolean deploymentStatus)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
@ -722,8 +831,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray revisionList = (JSONArray) new JSONObject(response.body().string()).get("list");
return jsonObject; return gson.fromJson(revisionList.toString(), APIRevision[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -747,16 +856,15 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision) public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions";
String apiRevisionDescription = "{\n" + JSONObject payload = new JSONObject();
" \"description\":\"" + apiRevision.getDescription() + "\"\n" + payload.put("description", (apiRevision.getDescription() != null ? apiRevision.getDescription() : null));
"}";
RequestBody requestBody = RequestBody.create(JSON, apiRevisionDescription); RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(addNewScope) .url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -767,8 +875,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) { if (HttpStatus.SC_CREATED == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); return gson.fromJson(response.body().string(), APIRevision.class);
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -799,15 +906,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId;
APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0); APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0);
String revision = "[\n" + JSONArray payload = new JSONArray();
" {\n" + JSONObject revision = new JSONObject();
" \"name\": \"" + apiRevisionDeployment.getDeployment() + "\",\n" + revision.put("name", (apiRevisionDeployment.getName() != null ? apiRevisionDeployment.getName() : ""));
" \"vhost\": \"" + apiRevisionDeployment.getVhost() + "\",\n" + revision.put("vhost", (apiRevisionDeployment.getVhost() != null ? apiRevisionDeployment.getVhost() : ""));
" \"displayOnDevportal\": " + apiRevisionDeployment.isDisplayOnDevportal() + "\n" + revision.put("displayOnDevportal", apiRevisionDeployment.isDisplayOnDevportal());
" }\n" + payload.put(revision);
"]";
RequestBody requestBody = RequestBody.create(JSON, revision); RequestBody requestBody = RequestBody.create(JSON, payload.toString());
Request request = new Request.Builder() Request request = new Request.Builder()
.url(deployAPIRevisionEndPoint) .url(deployAPIRevisionEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -844,23 +950,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
@Override @Override
public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevisionDeployment, String uuid) APIRevision apiRevisionDeployment, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId=" String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId="
+ apiRevisionDeployment.getString("id"); + apiRevisionDeployment.getId();
JSONArray array = apiRevisionDeployment.getJSONArray("deploymentInfo"); List<APIRevisionDeployment> apiRevisionDeployments = apiRevisionDeployment.getDeploymentInfo();
JSONObject obj = array.getJSONObject(0); APIRevisionDeployment earliestDeployment = apiRevisionDeployments.get(0);
String revision = "[\n" + JSONArray payload = new JSONArray();
" {\n" + JSONObject revision = new JSONObject();
" \"name\": \"" + obj.getString("name") + "\",\n" + revision.put("name", (earliestDeployment.getName() != null ? earliestDeployment.getName() : ""));
" \"vhost\": \"" + obj.getString("vhost") + "\",\n" + revision.put("vhost", (earliestDeployment.getVhost() != null ? earliestDeployment.getVhost() : ""));
" \"displayOnDevportal\": " + obj.get("displayOnDevportal") + "\n" + revision.put("displayOnDevportal", earliestDeployment.isDisplayOnDevportal());
" }\n" + payload.put(revision);
"]";
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
RequestBody requestBody = RequestBody.create(JSON, revision);
Request request = new Request.Builder() Request request = new Request.Builder()
.url(undeployAPIRevisionEndPoint) .url(undeployAPIRevisionEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
@ -896,11 +1001,11 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
@Override @Override
public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevision, String uuid) APIRevision apiRevision, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" +
apiRevision.getString("id"); apiRevision.getId();
Request request = new Request.Builder() Request request = new Request.Builder()
.url(apiRevisionEndPoint) .url(apiRevisionEndPoint)
@ -936,7 +1041,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
} }
@Override @Override
public JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) public Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000"; String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000";
@ -951,8 +1056,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) { if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string()); JSONArray documentList = (JSONArray) new JSONObject(response.body().string()).get("list");
return jsonObject; return gson.fromJson(documentList.toString(), Documentation[].class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices. AccessTokenInfo refreshedAccessToken = apiApplicationServices.
@ -1022,17 +1127,16 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents"; String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents";
String document = "{\n" + JSONObject payload = new JSONObject();
" \"name\": \"" + documentation.getName() + "\",\n" + payload.put("name", documentation.getName());
" \"type\": \"" + documentation.getType() + "\",\n" + payload.put("type", documentation.getType());
" \"summary\": \"" + documentation.getSummary() + "\",\n" + payload.put("summary", documentation.getSummary());
" \"sourceType\": \"" + documentation.getSourceType() + "\",\n" + payload.put("sourceType", documentation.getSourceType());
" \"inlineContent\": \"" + documentation.getSourceType() + "\",\n" + payload.put("inlineContent", documentation.getSourceType());
" \"visibility\": \"" + documentation.getVisibility() + "\",\n" + payload.put("visibility", documentation.getVisibility());
" \"createdBy\": \"admin\"\n" + payload.put("createdBy", documentation.getCreatedBy());
"}";
RequestBody requestBody = RequestBody.create(JSON, payload.toString());
RequestBody requestBody = RequestBody.create(JSON, document);
Request request = new Request.Builder() Request request = new Request.Builder()
.url(addNewScope) .url(addNewScope)
.addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON) .addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON)

@ -20,7 +20,7 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.*; import java.util.List;
/** /**
* This class represents the API response. * This class represents the API response.
@ -35,7 +35,7 @@ public class APIInfo {
private String version; private String version;
private String provider; private String provider;
private String lifeCycleStatus; private String lifeCycleStatus;
private String wsdlInfo; private type wsdlInfo;
private String wsdlUrl; private String wsdlUrl;
private boolean responseCachingEnabled; private boolean responseCachingEnabled;
private int cacheTimeout; private int cacheTimeout;
@ -45,59 +45,65 @@ public class APIInfo {
private String revisionedApiId; private String revisionedApiId;
private int revisionId; private int revisionId;
private boolean enableSchemaValidation; private boolean enableSchemaValidation;
private boolean enableStore;
private String type; private String type;
private Set<String> transport; private List<String> transport;
private Set<String> tags; private List<String> tags;
private Set<String> policies; private List<String> policies;
private String apiThrottlingPolicy; private String apiThrottlingPolicy;
private String authorizationHeader; private String authorizationHeader;
private String securityScheme; private List<String> securityScheme;
private String maxTps; private APIMaxTps maxTps;
private String visibility; private String visibility;
private String visibleRoles; private List<String> visibleRoles;
private String visibleTenants; private List<String> visibleTenants;
private String mediationPolicies; private List<MediationPolicy> mediationPolicies;
private String subscriptionAvailability; private String subscriptionAvailability;
private String subscriptionAvailableTenants; private List<String> subscriptionAvailableTenants;
private String additionalProperties; private List<AdditionalProperties> additionalProperties;
private String monetization; private Monetization monetization;
private String accessControl; private String accessControl;
private String accessControlRoles; private List<String> accessControlRoles;
private BusinessInformation businessInformation; private BusinessInformation businessInformation;
private CORSConfiguration corsConfiguration; private CORSConfiguration corsConfiguration;
private WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
private String workflowStatus; private String workflowStatus;
private String createdTime; private String createdTime;
private String lastUpdatedTime; private String lastUpdatedTime;
private JSONObject endpointConfig = new JSONObject(); private JSONObject endpointConfig;
private String endpointImplementationType; private String endpointImplementationType;
private List<JSONObject> scopes = new ArrayList(); private List<JSONObject> scopes;
private List<JSONObject> operations; private List<Operations> operations;
private String threatProtectionPolicies; private JSONObject threatProtectionPolicies;
private List<String> keyManagers = new ArrayList(); private List<String> categories;
private JSONObject serviceInfo = new JSONObject(); private List<String> keyManagers;
private ServiceInfo serviceInfo;
private AdvertiseInfo advertiseInfo; private AdvertiseInfo advertiseInfo;
private String asyncApiDefinition; public enum type {
WSDL, ZIP
private Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>(); }
private String inSequence;
private Map<String, String> wsUriMapping;
public String getId() { public String getId() {
return id; return id;
} }
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
@ -109,12 +115,15 @@ public class APIInfo {
public void setContext(String context) { public void setContext(String context) {
this.context = context; this.context = context;
} }
public String getVersion() { public String getVersion() {
return version; return version;
} }
public void setVersion(String version) { public void setVersion(String version) {
this.version = version; this.version = version;
} }
public String getProvider() { public String getProvider() {
return provider; return provider;
} }
@ -131,11 +140,11 @@ public class APIInfo {
this.lifeCycleStatus = lifeCycleStatus; this.lifeCycleStatus = lifeCycleStatus;
} }
public String getWsdlInfo() { public APIInfo.type getWsdlInfo() {
return wsdlInfo; return wsdlInfo;
} }
public void setWsdlInfo(String wsdlInfo) { public void setWsdlInfo(APIInfo.type wsdlInfo) {
this.wsdlInfo = wsdlInfo; this.wsdlInfo = wsdlInfo;
} }
@ -211,6 +220,14 @@ public class APIInfo {
this.enableSchemaValidation = enableSchemaValidation; this.enableSchemaValidation = enableSchemaValidation;
} }
public boolean isEnableStore() {
return enableStore;
}
public void setEnableStore(boolean enableStore) {
this.enableStore = enableStore;
}
public String getType() { public String getType() {
return type; return type;
} }
@ -219,27 +236,27 @@ public class APIInfo {
this.type = type; this.type = type;
} }
public Set<String> getTransport() { public List<String> getTransport() {
return transport; return transport;
} }
public void setTransport(Set<String> transport) { public void setTransport(List<String> transport) {
this.transport = transport; this.transport = transport;
} }
public Set<String> getTags() { public List<String> getTags() {
return tags; return tags;
} }
public void setTags(Set<String> tags) { public void setTags(List<String> tags) {
this.tags = tags; this.tags = tags;
} }
public Set<String> getPolicies() { public List<String> getPolicies() {
return policies; return policies;
} }
public void setPolicies(Set<String> policies) { public void setPolicies(List<String> policies) {
this.policies = policies; this.policies = policies;
} }
@ -259,19 +276,19 @@ public class APIInfo {
this.authorizationHeader = authorizationHeader; this.authorizationHeader = authorizationHeader;
} }
public String getSecurityScheme() { public List<String> getSecurityScheme() {
return securityScheme; return securityScheme;
} }
public void setSecurityScheme(String securityScheme) { public void setSecurityScheme(List<String> securityScheme) {
this.securityScheme = securityScheme; this.securityScheme = securityScheme;
} }
public String getMaxTps() { public APIMaxTps getMaxTps() {
return maxTps; return maxTps;
} }
public void setMaxTps(String maxTps) { public void setMaxTps(APIMaxTps maxTps) {
this.maxTps = maxTps; this.maxTps = maxTps;
} }
@ -283,27 +300,27 @@ public class APIInfo {
this.visibility = visibility; this.visibility = visibility;
} }
public String getVisibleRoles() { public List<String> getVisibleRoles() {
return visibleRoles; return visibleRoles;
} }
public void setVisibleRoles(String visibleRoles) { public void setVisibleRoles(List<String> visibleRoles) {
this.visibleRoles = visibleRoles; this.visibleRoles = visibleRoles;
} }
public String getVisibleTenants() { public List<String> getVisibleTenants() {
return visibleTenants; return visibleTenants;
} }
public void setVisibleTenants(String visibleTenants) { public void setVisibleTenants(List<String> visibleTenants) {
this.visibleTenants = visibleTenants; this.visibleTenants = visibleTenants;
} }
public String getMediationPolicies() { public List<MediationPolicy> getMediationPolicies() {
return mediationPolicies; return mediationPolicies;
} }
public void setMediationPolicies(String mediationPolicies) { public void setMediationPolicies(List<MediationPolicy> mediationPolicies) {
this.mediationPolicies = mediationPolicies; this.mediationPolicies = mediationPolicies;
} }
@ -315,27 +332,27 @@ public class APIInfo {
this.subscriptionAvailability = subscriptionAvailability; this.subscriptionAvailability = subscriptionAvailability;
} }
public String getSubscriptionAvailableTenants() { public List<String> getSubscriptionAvailableTenants() {
return subscriptionAvailableTenants; return subscriptionAvailableTenants;
} }
public void setSubscriptionAvailableTenants(String subscriptionAvailableTenants) { public void setSubscriptionAvailableTenants(List<String> subscriptionAvailableTenants) {
this.subscriptionAvailableTenants = subscriptionAvailableTenants; this.subscriptionAvailableTenants = subscriptionAvailableTenants;
} }
public String getAdditionalProperties() { public List<AdditionalProperties> getAdditionalProperties() {
return additionalProperties; return additionalProperties;
} }
public void setAdditionalProperties(String additionalProperties) { public void setAdditionalProperties(List<AdditionalProperties> additionalProperties) {
this.additionalProperties = additionalProperties; this.additionalProperties = additionalProperties;
} }
public String getMonetization() { public Monetization getMonetization() {
return monetization; return monetization;
} }
public void setMonetization(String monetization) { public void setMonetization(Monetization monetization) {
this.monetization = monetization; this.monetization = monetization;
} }
@ -347,11 +364,11 @@ public class APIInfo {
this.accessControl = accessControl; this.accessControl = accessControl;
} }
public String getAccessControlRoles() { public List<String> getAccessControlRoles() {
return accessControlRoles; return accessControlRoles;
} }
public void setAccessControlRoles(String accessControlRoles) { public void setAccessControlRoles(List<String> accessControlRoles) {
this.accessControlRoles = accessControlRoles; this.accessControlRoles = accessControlRoles;
} }
@ -371,6 +388,14 @@ public class APIInfo {
this.corsConfiguration = corsConfiguration; this.corsConfiguration = corsConfiguration;
} }
public WebsubSubscriptionConfiguration getWebsubSubscriptionConfiguration() {
return websubSubscriptionConfiguration;
}
public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfiguration websubSubscriptionConfiguration) {
this.websubSubscriptionConfiguration = websubSubscriptionConfiguration;
}
public String getWorkflowStatus() { public String getWorkflowStatus() {
return workflowStatus; return workflowStatus;
} }
@ -411,7 +436,7 @@ public class APIInfo {
this.endpointImplementationType = endpointImplementationType; this.endpointImplementationType = endpointImplementationType;
} }
public List<JSONObject>getScopes() { public List<JSONObject> getScopes() {
return scopes; return scopes;
} }
@ -419,22 +444,30 @@ public class APIInfo {
this.scopes = scopes; this.scopes = scopes;
} }
public List<JSONObject> getOperations() { public List<Operations> getOperations() {
return operations; return operations;
} }
public void setOperations(List<JSONObject> operations) { public void setOperations(List<Operations> operations) {
this.operations = operations; this.operations = operations;
} }
public String getThreatProtectionPolicies() { public JSONObject getThreatProtectionPolicies() {
return threatProtectionPolicies; return threatProtectionPolicies;
} }
public void setThreatProtectionPolicies(String threatProtectionPolicies) { public void setThreatProtectionPolicies(JSONObject threatProtectionPolicies) {
this.threatProtectionPolicies = threatProtectionPolicies; this.threatProtectionPolicies = threatProtectionPolicies;
} }
public List<String> getCategories() {
return categories;
}
public void setCategories(List<String> categories) {
this.categories = categories;
}
public List<String> getKeyManagers() { public List<String> getKeyManagers() {
return keyManagers; return keyManagers;
} }
@ -443,11 +476,11 @@ public class APIInfo {
this.keyManagers = keyManagers; this.keyManagers = keyManagers;
} }
public JSONObject getServiceInfo() { public ServiceInfo getServiceInfo() {
return serviceInfo; return serviceInfo;
} }
public void setServiceInfo(JSONObject serviceInfo) { public void setServiceInfo(ServiceInfo serviceInfo) {
this.serviceInfo = serviceInfo; this.serviceInfo = serviceInfo;
} }
@ -458,36 +491,4 @@ public class APIInfo {
public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) { public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) {
this.advertiseInfo = advertiseInfo; this.advertiseInfo = advertiseInfo;
} }
public String getInSequence() {
return inSequence;
}
public void setInSequence(String inSequence) {
this.inSequence = inSequence;
}
public String getAsyncApiDefinition() {
return asyncApiDefinition;
}
public void setAsyncApiDefinition(String asyncApiDefinition) {
this.asyncApiDefinition = asyncApiDefinition;
}
public Set<URITemplate> getUriTemplates() {
return uriTemplates;
}
public void setUriTemplates(Set<URITemplate> uriTemplates) {
this.uriTemplates = uriTemplates;
}
public Map<String, String> getWsUriMapping() {
return wsUriMapping;
}
public void setWsUriMapping(Map<String, String> wsUriMapping) {
this.wsUriMapping = wsUriMapping;
}
} }

@ -0,0 +1,44 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.io.Serializable;
public class APIMaxTps implements Serializable {
private static final long serialVersionUID = 1L;
int production;
int sandbox;
public int getProduction() {
return production;
}
public void setProduction(int production) {
this.production = production;
}
public int getSandbox() {
return sandbox;
}
public void setSandbox(int sandbox) {
this.sandbox = sandbox;
}
}

@ -17,26 +17,26 @@
*/ */
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
public class APIRevision implements Serializable { public class APIRevision implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private int id; private String id;
private String apiUUID; private String apiUUID;
private String revisionUUID; private String revisionUUID;
private String description; private String description;
private String displayName;
private String createdBy; private String createdBy;
private String createdTime; private String createdTime;
private List<APIRevisionDeployment> apiRevisionDeploymentList; private APIInfo apiInfo;
private List<APIRevisionDeployment> deploymentInfo;
public int getId() { public String getId() {
return id; return id;
} }
public void setId(int id) { public void setId(String id) {
this.id = id; this.id = id;
} }
@ -80,11 +80,28 @@ public class APIRevision implements Serializable {
this.createdTime = createdTime; this.createdTime = createdTime;
} }
public List<APIRevisionDeployment> getApiRevisionDeploymentList() { public List<APIRevisionDeployment> getDeploymentInfo() {
return apiRevisionDeploymentList; return deploymentInfo;
}
public void setDeploymentInfo(List<APIRevisionDeployment> deploymentInfo) {
this.deploymentInfo = deploymentInfo;
}
public String getDisplayName() {
return displayName;
} }
public void setApiRevisionDeploymentList(List<APIRevisionDeployment> apiRevisionDeploymentList) { public void setDisplayName(String displayName) {
this.apiRevisionDeploymentList = apiRevisionDeploymentList; this.displayName = displayName;
} }
public APIInfo getApiInfo() {
return apiInfo;
}
public void setApiInfo(APIInfo apiInfo) {
this.apiInfo = apiInfo;
}
} }

@ -23,10 +23,10 @@ import java.io.Serializable;
public class APIRevisionDeployment implements Serializable { public class APIRevisionDeployment implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private int id; private int id;
private String revisionUUID; private String revisionUuid;
private String deployment; private String name;
private String vhost; private String vhost;
private boolean isDisplayOnDevportal; private boolean displayOnDevportal;
private String deployedTime; private String deployedTime;
public int getId() { public int getId() {
@ -37,20 +37,20 @@ public class APIRevisionDeployment implements Serializable {
this.id = id; this.id = id;
} }
public String getRevisionUUID() { public String getRevisionUuid() {
return revisionUUID; return revisionUuid;
} }
public void setRevisionUUID(String revisionUUID) { public void setRevisionUuid(String revisionUuid) {
this.revisionUUID = revisionUUID; this.revisionUuid = revisionUuid;
} }
public String getDeployment() { public String getName() {
return deployment; return name;
} }
public void setDeployment(String deployment) { public void setName(String name) {
this.deployment = deployment; this.name = name;
} }
public String getVhost() { public String getVhost() {
@ -62,11 +62,11 @@ public class APIRevisionDeployment implements Serializable {
} }
public boolean isDisplayOnDevportal() { public boolean isDisplayOnDevportal() {
return isDisplayOnDevportal; return displayOnDevportal;
} }
public void setDisplayOnDevportal(boolean displayOnDevportal) { public void setDisplayOnDevportal(boolean displayOnDevportal) {
isDisplayOnDevportal = displayOnDevportal; this.displayOnDevportal = displayOnDevportal;
} }
public String getDeployedTime() { public String getDeployedTime() {

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class AdditionalProperties {
private String name;
private String value;
private boolean display;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isDisplay() {
return display;
}
public void setDisplay(boolean display) {
this.display = display;
}
}

@ -24,16 +24,21 @@ public class Documentation {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String id; private String id;
private String documentId; private String documentId;
private DocumentationType type;
private String name; private String name;
private DocumentationType type;
private String summary; private String summary;
private DocumentSourceType sourceType; private DocumentSourceType sourceType;
private String sourceUrl; private String sourceUrl;
private DocumentVisibility visibility; private String fileName;
private Date lastUpdated;
private String filePath; private String filePath;
private Date createdDate; private String inlineContent;
private String otherTypeName; private String otherTypeName;
private DocumentVisibility visibility;
private String createdTime;
private Date createdDate;
private String createdBy;
private Date lastUpdatedTime;
private String lastUpdatedBy;
public String getOtherTypeName() { public String getOtherTypeName() {
return this.otherTypeName; return this.otherTypeName;
@ -113,12 +118,12 @@ public class Documentation {
return result; return result;
} }
public Date getLastUpdated() { public Date getLastUpdatedTime() {
return this.lastUpdated; return this.lastUpdatedTime;
} }
public void setLastUpdated(Date lastUpdated) { public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdated = lastUpdated; this.lastUpdatedTime = lastUpdatedTime;
} }
public String getId() { public String getId() {
@ -145,6 +150,46 @@ public class Documentation {
this.createdDate = createdDate; this.createdDate = createdDate;
} }
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getInlineContent() {
return inlineContent;
}
public void setInlineContent(String inlineContent) {
this.inlineContent = inlineContent;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public static enum DocumentVisibility { public static enum DocumentVisibility {
OWNER_ONLY("owner_only"), OWNER_ONLY("owner_only"),
PRIVATE("private"), PRIVATE("private"),

@ -0,0 +1,59 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class MediationPolicy {
private String id;
private String name;
private String type;
private boolean shared;
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.json.JSONObject;
public class Monetization {
private boolean enabled;
private JSONObject properties;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public JSONObject getProperties() {
return properties;
}
public void setProperties(JSONObject properties) {
this.properties = properties;
}
}

@ -18,7 +18,8 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.util.Set; import org.json.JSONObject;
import java.util.List;
/** /**
* This hold the api operations information. * This hold the api operations information.
@ -29,8 +30,8 @@ public class Operations {
private String verb; private String verb;
private String authType; private String authType;
private String throttlingPolicy; private String throttlingPolicy;
private Set<String> scopes; private List<String> scopes;
private String usedProductIds; private List<String> usedProductIds;
private String amznResourceName; private String amznResourceName;
private String amznResourceTimeout; private String amznResourceTimeout;
private String payloadSchema; private String payloadSchema;
@ -78,19 +79,19 @@ public class Operations {
this.throttlingPolicy = throttlingPolicy; this.throttlingPolicy = throttlingPolicy;
} }
public Set<String> getScopes() { public List<String> getScopes() {
return scopes; return scopes;
} }
public void setScopes(Set<String> scopes) { public void setScopes(List<String> scopes) {
this.scopes = scopes; this.scopes = scopes;
} }
public String getUsedProductIds() { public List<String> getUsedProductIds() {
return usedProductIds; return usedProductIds;
} }
public void setUsedProductIds(String usedProductIds) { public void setUsedProductIds(List<String> usedProductIds) {
this.usedProductIds = usedProductIds; this.usedProductIds = usedProductIds;
} }

@ -18,25 +18,29 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo; package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.HashSet;
public class Scope implements Serializable{ public class Scope implements Serializable{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
String key; String id;
String name; String name;
String roles; String displayName;
String description; String description;
String id; List<String> bindings;
int usageCount; int usageCount;
public String getKey() { public String getDisplayName() {
return key; return displayName;
} }
public void setKey(String key) { public void setDisplayName(String displayName) {
this.key = key; this.displayName = displayName;
} }
public String getName() { public String getName() {
@ -47,12 +51,12 @@ public class Scope implements Serializable{
this.name = name; this.name = name;
} }
public String getRoles() { public List<String> getBindings() {
return roles; return bindings;
} }
public void setRoles(String roles) { public void setBindings(List<String> bindings) {
this.roles = roles; this.bindings = removeDuplicatesFromRoleString(bindings);
} }
public String getDescription() { public String getDescription() {
@ -87,14 +91,22 @@ public class Scope implements Serializable{
Scope scope = (Scope) o; Scope scope = (Scope) o;
if (id != null ? !id.equals(scope.id) : scope.id != null) return false; if (id != null ? !id.equals(scope.id) : scope.id != null) return false;
if (!key.equals(scope.key)) return false;
if (!name.equals(scope.name)) return false; if (!name.equals(scope.name)) return false;
if (roles != null ? !roles.equals(scope.roles) : scope.roles != null) return false; if (!displayName.equals(scope.displayName)) return false;
if (bindings != null ? !bindings.equals(scope.bindings) : scope.bindings != null) return false;
return description != null ? description.equals(scope.description) : scope.description == null; return description != null ? description.equals(scope.description) : scope.description == null;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(key, name, roles, description, id); return Objects.hash(name, displayName, bindings, description, id);
}
private static List<String> removeDuplicatesFromRoleString(List<String> roles) {
Set<String> roleSet = new HashSet<>();
for(String role : roles) {
roleSet.add(role.trim());
}
return new ArrayList<>(roleSet);
} }
} }

@ -0,0 +1,59 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class ServiceInfo {
private String key;
private String name;
private String version;
private boolean outdated;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isOutdated() {
return outdated;
}
public void setOutdated(boolean outdated) {
this.outdated = outdated;
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
public class ThreatProtectionPolicies {
private String policyID;
private int priority;
public String getPolicyID() {
return policyID;
}
public void setPolicyID(String policyID) {
this.policyID = policyID;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
}

@ -0,0 +1,61 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
/**
* This hold the Websub Subscription Configuration of an API.
*/
public class WebsubSubscriptionConfiguration {
private boolean enable;
private String secret;
private String signingAlgorithm;
private String signatureHeader;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getSigningAlgorithm() {
return signingAlgorithm;
}
public void setSigningAlgorithm(String signingAlgorithm) {
this.signingAlgorithm = signingAlgorithm;
}
public String getSignatureHeader() {
return signatureHeader;
}
public void setSignatureHeader(String signatureHeader) {
this.signatureHeader = signatureHeader;
}
}

@ -1,90 +0,0 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.util;
import java.util.HashSet;
import java.util.Set;
/**
* This class represents the scope data.
*/
public class ScopeUtils {
private String key;
private String name;
private String roles;
private String description;
private int id;
public ScopeUtils() {
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = removeDuplicatesFromRoleString(roles);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toJSON() {
String jsonString = "{\n" +
" \"name\":\"" + key + "\",\n" +
" \"displayName\":\"" + name + "\",\n" +
" \"description\":\"" + description + "\",\n" +
" \"bindings\":[\n" +
" \"" + roles + "\"\n" +
" ]\n" +
"}";
return jsonString;
}
private static String removeDuplicatesFromRoleString(String roleString) {
String[] roles = roleString.split(",");
Set<String> roleSet = new HashSet<>();
for(String role : roles) {
roleSet.add(role.trim());
}
return String.join(",", roleSet);
}
}

@ -17,19 +17,15 @@
*/ */
package io.entgra.device.mgt.core.apimgt.webapp.publisher; package io.entgra.device.mgt.core.apimgt.webapp.publisher;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; 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.PublisherRESTAPIServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.CORSConfiguration;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
@ -91,6 +87,7 @@ import java.util.Date;
*/ */
public class APIPublisherServiceImpl implements APIPublisherService { public class APIPublisherServiceImpl implements APIPublisherService {
public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance(); public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance();
private static final Gson gson = new Gson();
private static final String UNLIMITED_TIER = "Unlimited"; private static final String UNLIMITED_TIER = "Unlimited";
private static final String WS_UNLIMITED_TIER = "AsyncUnlimited"; private static final String WS_UNLIMITED_TIER = "AsyncUnlimited";
private static final String API_PUBLISH_ENVIRONMENT = "Default"; private static final String API_PUBLISH_ENVIRONMENT = "Default";
@ -100,7 +97,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT"; public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT";
public static final String API_GLOBAL_VISIBILITY = "PUBLIC"; public static final String API_GLOBAL_VISIBILITY = "PUBLIC";
public static final String API_PRIVATE_VISIBILITY = "PRIVATE"; public static final String API_PRIVATE_VISIBILITY = "PRIVATE";
private static final String ADMIN_ROLE_KEY = ",admin"; private static final String ADMIN_ROLE_KEY = "admin";
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
@ -166,14 +163,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiConfig.getName(), apiConfig.getVersion()); apiConfig.getName(), apiConfig.getVersion());
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONArray apiList = (JSONArray) publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo).get("list"); APIInfo[] apiList = publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo);
boolean apiFound = false; boolean apiFound = false;
for (int i = 0; i < apiList.length(); i++) { for (int i = 0; i < apiList.length; i++) {
JSONObject apiObj = apiList.getJSONObject(i); APIInfo apiObj = apiList[i];
if (apiObj.getString("name").equals(apiIdentifier.getApiName().replace(Constants.SPACE, if (apiObj.getName().equals(apiIdentifier.getApiName().replace(Constants.SPACE,
Constants.EMPTY_STRING))) { Constants.EMPTY_STRING))) {
apiFound = true; apiFound = true;
apiIdentifier.setUuid(apiObj.getString("id")); apiIdentifier.setUuid(apiObj.getId());
break; break;
} }
} }
@ -184,21 +181,23 @@ public class APIPublisherServiceImpl implements APIPublisherService {
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo,
apiScope.getKey())) { apiScope.getKey())) {
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(apiScope.getName()); scope.setDisplayName(apiScope.getName());
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setName(apiScope.getKey());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); List<String> bindings = apiScope.getRoles();
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
APIInfo api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api);
apiUuid = createdAPI.getString("id"); apiUuid = createdAPI.getId();
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
apiUuid, apiConfig.getAsyncApiDefinition()); apiUuid, apiConfig.getAsyncApiDefinition());
} }
if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) { if (CREATED_STATUS.equals(createdAPI.getLifeCycleStatus())) {
// if endpoint type "dynamic" and then add in sequence // if endpoint type "dynamic" and then add in sequence
if ("dynamic".equals(apiConfig.getEndpointType())) { if ("dynamic".equals(apiConfig.getEndpointType())) {
Mediation mediation = new Mediation(); Mediation mediation = new Mediation();
@ -216,10 +215,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiRevision.setApiUUID(apiUuid); apiRevision.setApiUUID(apiUuid);
apiRevision.setDescription("Initial Revision"); apiRevision.setDescription("Initial Revision");
String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id"); accessTokenInfo, apiRevision).getId();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host")); apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host"));
apiRevisionDeployment.setDisplayOnDevportal(true); apiRevisionDeployment.setDisplayOnDevportal(true);
@ -257,10 +256,12 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} else { } else {
// if new scope add as shared scope // if new scope add as shared scope
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(apiScope.getName()); scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setDisplayName(apiScope.getName());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); List<String> bindings = apiScope.getRoles();
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
@ -268,27 +269,29 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
// Get existing API // Get existing API
JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo,
apiUuid); apiUuid);
if (scopesToMoveAsSharedScopes.size() > 0) { if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes // update API to remove local scopes
APIInfo api = getAPI(apiConfig, false); APIInfo api = getAPI(apiConfig, false);
api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus")); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) { for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(apiScope.getName()); scope.setName(apiScope.getKey());
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setDisplayName(apiScope.getName());
scope.setRoles(apiScope.getRoles() + ADMIN_ROLE_KEY); List<String> bindings = apiScope.getRoles();
bindings.add(ADMIN_ROLE_KEY);
scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid);
APIInfo api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus")); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus());
api.setId(apiUuid); api.setId(apiUuid);
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
@ -305,15 +308,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setType("in"); mediation.setType("in");
mediation.setGlobal(false); mediation.setGlobal(false);
JSONArray mediationList = (JSONArray) publisherRESTAPIServices MediationPolicy[] mediationList = publisherRESTAPIServices
.getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiUuid);
apiUuid).get("list");
boolean isMediationPolicyFound = false; boolean isMediationPolicyFound = false;
for (int i = 0; i < mediationList.length(); i++) { for (int i = 0; i < mediationList.length; i++) {
JSONObject mediationObj = mediationList.getJSONObject(i); MediationPolicy mediationPolicy = mediationList[i];
if (apiConfig.getInSequenceName().equals(mediationObj.getString("name"))) { if (apiConfig.getInSequenceName().equals(mediationPolicy.getName())) {
mediation.setUuid(mediationObj.getString("id")); mediation.setUuid(mediationPolicy.getId());
publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey, publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey,
accessTokenInfo, apiUuid, mediation); accessTokenInfo, apiUuid, mediation);
publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
@ -328,24 +330,22 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} }
int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
accessTokenInfo, apiUuid, null).get("count"); accessTokenInfo, apiUuid, null).length;
if (apiRevisionCount >= 5) { if (apiRevisionCount >= 5) {
// This will retrieve the deployed revision // This will retrieve the deployed revision
JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions( APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions(
apiApplicationKey, accessTokenInfo, apiUuid, apiApplicationKey, accessTokenInfo, apiUuid, true);
true).get("list"); if (revisionDeploymentList.length > 0) {
if (revisionDeploymentList.length() > 0) { APIRevision latestRevisionDeployment = revisionDeploymentList[0];
JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0);
publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey,
accessTokenInfo, latestRevisionDeployment, apiUuid); accessTokenInfo, latestRevisionDeployment, apiUuid);
} }
// This will retrieve the un deployed revision list // This will retrieve the undeployed revision list
JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions( APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
apiApplicationKey, accessTokenInfo, apiUuid, accessTokenInfo, apiUuid, false);
false).get("list"); if (undeployedRevisionList.length > 0) {
if (undeployedRevisionList.length() > 0) { APIRevision earliestUndeployRevision = undeployedRevisionList[0];
JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0);
publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo,
earliestUndeployRevision, apiUuid); earliestUndeployRevision, apiUuid);
} }
@ -356,10 +356,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiRevision.setApiUUID(apiUuid); apiRevision.setApiUUID(apiUuid);
apiRevision.setDescription("Updated Revision"); apiRevision.setDescription("Updated Revision");
String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id"); accessTokenInfo, apiRevision).getId();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host")); apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host"));
apiRevisionDeployment.setDisplayOnDevportal(true); apiRevisionDeployment.setDisplayOnDevportal(true);
@ -369,7 +369,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo,
apiUuid, apiRevisionId, apiRevisionDeploymentList); apiUuid, apiRevisionId, apiRevisionDeploymentList);
if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) { if (CREATED_STATUS.equals(existingAPI.getLifeCycleStatus())) {
publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo,
apiUuid, PUBLISH_ACTION); apiUuid, PUBLISH_ACTION);
} }
@ -397,27 +397,27 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiDocumentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL); apiDocumentation.setVisibility(Documentation.DocumentVisibility.API_LEVEL);
apiDocumentation.setSourceType(Documentation.DocumentSourceType.MARKDOWN); apiDocumentation.setSourceType(Documentation.DocumentSourceType.MARKDOWN);
apiDocumentation.setCreatedDate(new Date()); apiDocumentation.setCreatedDate(new Date());
apiDocumentation.setLastUpdated(new Date()); apiDocumentation.setLastUpdatedTime(new Date());
apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary());
apiDocumentation.setOtherTypeName(null); apiDocumentation.setOtherTypeName(null);
JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey, Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiApplicationKey,
accessTokenInfo, apiUuid).get("list"); accessTokenInfo, apiUuid);
if (documentList.length() > 0) { if (documentList.length > 0) {
for (int i = 0; i < documentList.length(); i++) { for (int i = 0; i < documentList.length; i++) {
JSONObject existingDoc = documentList.getJSONObject(i); Documentation existingDoc = documentList[i];
if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName()) if (existingDoc.getName().equals(apiConfig.getApiDocumentationName())
&& existingDoc.getString("type").equals(Documentation.DocumentationType.HOWTO.name())) { && existingDoc.getType().equals(Documentation.DocumentationType.HOWTO.name())) {
publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo,
apiUuid, existingDoc.getString("documentId")); apiUuid, existingDoc.getDocumentId());
} }
} }
} else { } else {
log.info("There is no any existing api documentation."); log.info("There is no any existing api documentation.");
} }
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo,
apiUuid, apiDocumentation); apiUuid, apiDocumentation);
publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid, publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid,
@ -458,10 +458,15 @@ public class APIPublisherServiceImpl implements APIPublisherService {
for (DefaultPermission defaultPermission: defaultPermissions.getDefaultPermissions()) { for (DefaultPermission defaultPermission: defaultPermissions.getDefaultPermissions()) {
//todo check whether scope is available or not //todo check whether scope is available or not
ScopeMapping scopeMapping = defaultPermission.getScopeMapping(); ScopeMapping scopeMapping = defaultPermission.getScopeMapping();
scope.setName(scopeMapping.getName());
String[] roles = scopeMapping.getDefaultRoles().split(",");
List<String> bindings = Arrays.asList(roles);
bindings.add(ADMIN_ROLE_KEY);
scope.setName(scopeMapping.getKey());
scope.setDescription(scopeMapping.getName()); scope.setDescription(scopeMapping.getName());
scope.setKey(scopeMapping.getKey()); scope.setDisplayName(scopeMapping.getName());
scope.setRoles(scopeMapping.getDefaultRoles() + ADMIN_ROLE_KEY); scope.setBindings(bindings);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} catch (BadRequestException | UnexpectedResponseException | APIServicesException e) { } catch (BadRequestException | UnexpectedResponseException | APIServicesException e) {
@ -497,7 +502,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
try { try {
String fileName = String fileName =
@ -543,52 +547,43 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName( scope.setDisplayName(
scopeMapping[0] != null ? StringUtils.trim(scopeMapping[0]) : StringUtils.EMPTY); scopeMapping[0] != null ? StringUtils.trim(scopeMapping[0]) : StringUtils.EMPTY);
scope.setDescription( scope.setDescription(
scopeMapping[1] != null ? StringUtils.trim(scopeMapping[1]) : StringUtils.EMPTY); scopeMapping[1] != null ? StringUtils.trim(scopeMapping[1]) : StringUtils.EMPTY);
scope.setKey( scope.setName(
scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY); scopeMapping[2] != null ? StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY);
// scope.setPermissions( // scope.setPermissions(
// scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY); // scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY);
String permission = scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY; String permission = scopeMapping[3] != null ? StringUtils.trim(scopeMapping[3]) : StringUtils.EMPTY;
String roleString = ""; List<String> rolesList = new ArrayList<>();
for (int i = 4; i < scopeMapping.length; i++) { for (int i = 4; i < scopeMapping.length; i++) {
if (scopeMapping[i] != null && StringUtils.trim(scopeMapping[i]).equals("Yes")) { if (scopeMapping[i] != null && StringUtils.trim(scopeMapping[i]).equals("Yes")) {
roleString = roleString + "," + roles.get(i); rolesList.add(roles.get(i));
if (rolePermissions.containsKey(roles.get(i)) && StringUtils.isNotEmpty(permission)) { if (rolePermissions.containsKey(roles.get(i)) && StringUtils.isNotEmpty(permission)) {
rolePermissions.get(roles.get(i)).add(permission); rolePermissions.get(roles.get(i)).add(permission);
} }
} }
} }
if (roleString.length() > 1) { //Set scope details which related to the scope key
roleString = roleString.substring(1); // remove first , (comma) Scope[] scopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
} for (int i = 0; i < scopes.length; i++) {
scope.setRoles(roleString); Scope relatedScope = scopes[i];
if (relatedScope.getName().equals(scopeMapping[2].toString())) {
//Set scope id which related to the scope key scope.setId(relatedScope.getId());
JSONArray scopeList = (JSONArray) scopeObject.get("list"); scope.setUsageCount(relatedScope.getUsageCount());
for (int i = 0; i < scopeList.length(); i++) { //Including already existing roles
JSONObject scopeObj = scopeList.getJSONObject(i); rolesList.addAll(relatedScope.getBindings());
if (scopeObj.getString("name").equals(scopeMapping[2] != null ?
StringUtils.trim(scopeMapping[2]) : StringUtils.EMPTY)) {
scope.setId(scopeObj.getString("id"));
// Including already existing roles
JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings");
for (int j = 0; j < existingRolesArray.length(); j++) {
roleString = roleString + "," + existingRolesArray.get(j);
}
} }
} }
scope.setRoles(roleString); scope.setBindings(rolesList);
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
} else { } else {
// todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list
log.warn(scope.getKey() + " not available as shared scope"); log.warn(scope.getName() + " not available as shared scope");
} }
} }
for (String role : rolePermissions.keySet()) { for (String role : rolePermissions.keySet()) {
@ -601,12 +596,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} catch (IOException | DirectoryIteratorException ex) { } catch (IOException | DirectoryIteratorException ex) {
log.error("failed to read scopes from file.", ex); log.error("failed to read scopes from file.", ex);
} catch (APIServicesException | BadRequestException e) {
String errorMsg = "Error while calling APIs";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
} }
} }
} catch (APIServicesException e) { } catch (APIServicesException e) {
String errorMsg = "Error while processing Publisher REST API response"; String errorMsg = "Error while processing Publisher REST API response";
@ -642,13 +632,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
try { try {
PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONObject scopeObject = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
Map<String, String> permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); Map<String, String> permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping();
if (permissions.length != 0) { if (permissions.length != 0) {
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, permissions, permScopeMap, false); updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, permissions, permScopeMap, false);
} }
if (removedPermissions.length != 0) { if (removedPermissions.length != 0) {
updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeObject, removedPermissions, permScopeMap, true); updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, removedPermissions, permScopeMap, true);
} }
try { try {
@ -680,7 +671,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
* @param publisherRESTAPIServices {@link PublisherRESTAPIServices} * @param publisherRESTAPIServices {@link PublisherRESTAPIServices}
* @param apiApplicationKey {@link APIApplicationKey} * @param apiApplicationKey {@link APIApplicationKey}
* @param accessTokenInfo {@link AccessTokenInfo} * @param accessTokenInfo {@link AccessTokenInfo}
* @param scopeObject scope object returning from APIM * @param scopeList scope list returning from APIM
* @param permissions List of permissions * @param permissions List of permissions
* @param permScopeMap Permission Scope map * @param permScopeMap Permission Scope map
* @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false. * @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false.
@ -688,7 +679,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
*/ */
private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices,
APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject scopeObject, String[] permissions, Map<String, String> permScopeMap, boolean removingPermissions ) Scope[] scopeList, String[] permissions, Map<String, String> permScopeMap, boolean removingPermissions )
throws APIManagerPublisherException { throws APIManagerPublisherException {
for (String permission : permissions) { for (String permission : permissions) {
String scopeValue = permScopeMap.get(permission); String scopeValue = permScopeMap.get(permission);
@ -699,22 +690,21 @@ public class APIPublisherServiceImpl implements APIPublisherService {
throw new APIManagerPublisherException(msg); throw new APIManagerPublisherException(msg);
} }
JSONArray scopeList = (JSONArray) scopeObject.get("list"); for (int i = 0; i < scopeList.length; i++) {
for (int i = 0; i < scopeList.length(); i++) { Scope scopeObj = scopeList[i];
JSONObject scopeObj = scopeList.getJSONObject(i); if (scopeObj.getName().equals(scopeValue)) {
if (scopeObj.getString("name").equals(scopeValue)) {
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(scopeObj.getString("name")); scope.setName(scopeObj.getName());
scope.setKey(scopeObj.getString("name")); scope.setDisplayName(scopeObj.getDisplayName());
scope.setDescription(scopeObj.getString("description")); scope.setDescription(scopeObj.getDescription());
scope.setId(scopeObj.getString("id")); scope.setId(scopeObj.getId());
// Including already existing roles // Including already existing roles
JSONArray existingRolesArray = (JSONArray) scopeObj.get("bindings"); List<String> existingRoleList = new ArrayList<>();
List<String> existingRoleList = new ArrayList<String>(); existingRoleList.addAll(scopeObj.getBindings());
for (int j = 0; j < existingRolesArray.length(); j++) { if (!existingRoleList.contains(roleName)) {
existingRoleList.add((String) existingRolesArray.get(j)); existingRoleList.add(roleName);
} }
if (removingPermissions) { if (removingPermissions) {
@ -724,14 +714,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
existingRoleList.add(roleName); existingRoleList.add(roleName);
} }
} }
scope.setRoles(String.join(",", existingRoleList)); scope.setBindings(existingRoleList);
try { try {
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getKey())) { if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
} else { } else {
// todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list
log.warn(scope.getKey() + " not available as shared scope"); log.warn(scope.getName() + " not available as shared scope");
} }
} catch (APIServicesException | BadRequestException | UnexpectedResponseException e) { } catch (APIServicesException | BadRequestException | UnexpectedResponseException e) {
log.error("Error occurred while updating role scope mapping via APIM REST endpoint.", e); log.error("Error occurred while updating role scope mapping via APIM REST endpoint.", e);
@ -783,55 +773,49 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiInfo.setRevisionedApiId(null); apiInfo.setRevisionedApiId(null);
apiInfo.setEnableSchemaValidation(false); apiInfo.setEnableSchemaValidation(false);
Set<String> tags = new HashSet<>(); List<String> tags = new ArrayList<>();
tags.addAll(Arrays.asList(config.getTags())); tags.addAll(Arrays.asList(config.getTags()));
apiInfo.setTags(tags); apiInfo.setTags(tags);
Set<String> availableTiers = new HashSet<>(); List<String> availableTiers = new ArrayList<>();
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
availableTiers.add(WS_UNLIMITED_TIER); availableTiers.add(WS_UNLIMITED_TIER);
} else { } else {
availableTiers.add(UNLIMITED_TIER); availableTiers.add(UNLIMITED_TIER);
} }
apiInfo.setPolicies(availableTiers); apiInfo.setPolicies(availableTiers);
apiInfo.setApiThrottlingPolicy(UNLIMITED_TIER);
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
apiInfo.setAsyncApiDefinition(config.getAsyncApiDefinition());
}
//set operations and scopes //set operations and scopes
List<JSONObject> operations = new ArrayList(); List<Operations> operations = new ArrayList();
List<JSONObject> scopeSet = new ArrayList(); List<JSONObject> scopeSet = new ArrayList();
Iterator<ApiUriTemplate> iterator; Iterator<ApiUriTemplate> iterator;
for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) {
ApiUriTemplate apiUriTemplate = iterator.next(); ApiUriTemplate apiUriTemplate = iterator.next();
JSONObject operation = new JSONObject(); Operations operation = new Operations();
operation.put("target", apiUriTemplate.getUriTemplate()); operation.setTarget(apiUriTemplate.getUriTemplate());
operation.put("verb", apiUriTemplate.getHttpVerb()); operation.setVerb(apiUriTemplate.getHttpVerb());
operation.put("authType", apiUriTemplate.getAuthType()); operation.setAuthType(apiUriTemplate.getAuthType());
operation.put("throttlingPolicy", UNLIMITED_TIER); operation.setThrottlingPolicy(UNLIMITED_TIER);
operation.put("uriMapping", apiUriTemplate.getUriMapping()); operation.setUriMapping(apiUriTemplate.getUriMapping());
if (includeScopes) { if (includeScopes) {
if (apiUriTemplate.getScope() != null) { if (apiUriTemplate.getScope() != null) {
String scopeString = "{\n" + Scope scope = new Scope();
" \"scope\": {\n" + scope.setName(apiUriTemplate.getScope().getKey());
" \"id\": null,\n" + scope.setDisplayName(apiUriTemplate.getScope().getName());
" \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" + scope.setDescription(apiUriTemplate.getScope().getDescription());
" \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" + scope.setBindings(apiUriTemplate.getScope().getRoles());
" \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" +
" \"bindings\": [\n" + JSONObject scopeObject = new JSONObject();
" \"" + apiUriTemplate.getScope().getRoles() + "\"\n" + scopeObject.put("scope", new JSONObject(gson.toJson(scope)));
" ],\n" + scopeObject.put("shared", true);
" \"usageCount\": null\n" +
" },\n" + scopeSet.add(scopeObject);
" \"shared\": true\n" +
" }";
JSONObject scope = new JSONObject(scopeString);
scopeSet.add(scope);
Set<String> scopes = new HashSet<>(); List<String> scopes = new ArrayList<>();
scopes.add(apiUriTemplate.getScope().getKey()); scopes.addAll(Arrays.asList(apiUriTemplate.getScope().getKey()));
operation.put("scopes", scopes); operation.setScopes(scopes);
} }
} }
operations.add(operation); operations.add(operation);
@ -859,8 +843,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }"; " }";
JSONObject endPointConfig = new JSONObject(endpointConfig); JSONObject endPointConfig = new JSONObject(endpointConfig);
Set<String> transports = new HashSet<>(); List<String> transports = new ArrayList<>();
transports.addAll(Arrays.asList(config.getTransports())); transports.addAll(Arrays.asList(config.getTransports().split(",")));
apiInfo.setTransport(transports); apiInfo.setTransport(transports);
apiInfo.setType("HTTP"); apiInfo.setType("HTTP");
@ -876,7 +860,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }\n" + " }\n" +
" }"; " }";
endPointConfig = new JSONObject(endpointConfig); endPointConfig = new JSONObject(endpointConfig);
apiInfo.setInSequence(config.getInSequenceName()); apiInfo.setEndpointImplementationType("ENDPOINT");
} }
// if ws endpoint // if ws endpoint
@ -892,7 +876,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
" }"; " }";
endPointConfig = new JSONObject(endpointConfig); endPointConfig = new JSONObject(endpointConfig);
transports.addAll(Arrays.asList("wss,ws")); transports.add("wss");
transports.add("ws");
apiInfo.setTransport(transports); apiInfo.setTransport(transports);
apiInfo.setType("WS"); apiInfo.setType("WS");
} }
@ -926,6 +911,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiInfo.setEnableSchemaValidation(false); apiInfo.setEnableSchemaValidation(false);
apiInfo.setMonetization(null); apiInfo.setMonetization(null);
apiInfo.setServiceInfo(null); apiInfo.setServiceInfo(null);
apiInfo.setWebsubSubscriptionConfiguration(null);
apiInfo.setAdvertiseInfo(null);
return apiInfo; return apiInfo;
} }

@ -18,11 +18,13 @@
package io.entgra.device.mgt.core.apimgt.webapp.publisher.dto; package io.entgra.device.mgt.core.apimgt.webapp.publisher.dto;
import java.util.List;
public class ApiScope { public class ApiScope {
String key; String key;
String name; String name;
String roles; List<String> roles;
String permissions; String permissions;
String description; String description;
int id; int id;
@ -46,11 +48,11 @@ public class ApiScope {
this.name = name; this.name = name;
} }
public String getRoles() { public List<String> getRoles() {
return this.roles; return this.roles;
} }
public void setRoles(String roles) { public void setRoles(List<String> roles) {
this.roles = roles; this.roles = roles;
} }

@ -228,10 +228,9 @@ public class AnnotationProcessor {
String permissions[]; String permissions[];
StringBuilder aggregatedPermissions; StringBuilder aggregatedPermissions;
String roles[]; String roles[];
StringBuilder aggregatedRoles; List<String> aggregatedRoles;
for (int i = 0; i < annotatedScopes.length; i++) { for (int i = 0; i < annotatedScopes.length; i++) {
aggregatedPermissions = new StringBuilder(); aggregatedPermissions = new StringBuilder();
aggregatedRoles = new StringBuilder();
methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]); methodHandler = Proxy.getInvocationHandler(annotatedScopes[i]);
scope = new ApiScope(); scope = new ApiScope();
scope.setName(invokeMethod(scopeClass scope.setName(invokeMethod(scopeClass
@ -250,11 +249,8 @@ public class AnnotationProcessor {
scope.setPermissions(aggregatedPermissions.toString().trim()); scope.setPermissions(aggregatedPermissions.toString().trim());
roles = (String[]) methodHandler.invoke(annotatedScopes[i], scopeClass roles = (String[]) methodHandler.invoke(annotatedScopes[i], scopeClass
.getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_ROLES, null), null); .getMethod(SWAGGER_ANNOTATIONS_PROPERTIES_ROLES, null), null);
for (String role : roles) { aggregatedRoles = Arrays.asList(roles);
aggregatedRoles.append(role); scope.setRoles(aggregatedRoles);
aggregatedRoles.append(",");
}
scope.setRoles(aggregatedRoles.substring(0, aggregatedRoles.lastIndexOf(",")));
scopes.put(scope.getKey(), scope); scopes.put(scope.getKey(), scope);
} }
return scopes; return scopes;
@ -305,11 +301,13 @@ public class AnnotationProcessor {
// } else { // } else {
// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + // log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
// makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
// List<String> roles = new ArrayList<>();
// roles.add(DEFAULT_SCOPE_ROLE);
// scope = new ApiScope(); // scope = new ApiScope();
// scope.setName(DEFAULT_SCOPE_NAME); // scope.setName(DEFAULT_SCOPE_NAME);
// scope.setDescription(DEFAULT_SCOPE_NAME); // scope.setDescription(DEFAULT_SCOPE_NAME);
// scope.setKey(DEFAULT_SCOPE_KEY); // scope.setKey(DEFAULT_SCOPE_KEY);
// scope.setRoles(DEFAULT_SCOPE_ROLE); // scope.setRoles(roles);
// scope.setPermissions(DEFAULT_SCOPE_PERMISSION); // scope.setPermissions(DEFAULT_SCOPE_PERMISSION);
// resource.setScope(scope); // resource.setScope(scope);
// } // }
@ -543,11 +541,13 @@ public class AnnotationProcessor {
} else { } else {
// log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) + // log.warn("Scope is not defined for '" + makeContextURLReady(resourceRootContext) +
// makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope"); // makeContextURLReady(subCtx) + "' endpoint, hence assigning the default scope");
List<String> roles = new ArrayList<>();
roles.add(DEFAULT_SCOPE_ROLE);
scope = new ApiScope(); scope = new ApiScope();
scope.setName(DEFAULT_SCOPE_NAME); scope.setName(DEFAULT_SCOPE_NAME);
scope.setDescription(DEFAULT_SCOPE_NAME); scope.setDescription(DEFAULT_SCOPE_NAME);
scope.setKey(DEFAULT_SCOPE_KEY); scope.setKey(DEFAULT_SCOPE_KEY);
scope.setRoles(DEFAULT_SCOPE_ROLE); scope.setRoles(roles);
scope.setPermissions(DEFAULT_SCOPE_PERMISSION); scope.setPermissions(DEFAULT_SCOPE_PERMISSION);
apiResource.setScope(scope); apiResource.setScope(scope);
} }

@ -39,7 +39,7 @@ public class TestUtils {
ApiScope scope = new ApiScope(); ApiScope scope = new ApiScope();
scope.setKey("win:ops:reboot"); scope.setKey("win:ops:reboot");
scope.setName("Reboot"); scope.setName("Reboot");
scope.setRoles("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot"); scope.setPermissions("/permission/admin/device-mgt/devices/owning-device/operations/windows/reboot");
scope.setDescription("Lock reset on Windows devices"); scope.setDescription("Lock reset on Windows devices");
template.setScope(scope); template.setScope(scope);
uriTemplates.add(template); uriTemplates.add(template);

Loading…
Cancel
Save