Implement on progress publisher api layer

syncHierarchicalGrouping
Pasindu Rupasinghe 2 years ago
parent 89132f4824
commit fa3c112a68

@ -34,6 +34,11 @@
<url>https://entgra.io</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>org.wso2.carbon.logging</artifactId>

@ -24,7 +24,9 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIService
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.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 org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.*;
import java.util.List;
public interface PublisherRESTAPIServices { public interface PublisherRESTAPIServices {
@ -34,6 +36,53 @@ public interface PublisherRESTAPIServices {
boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, String asyncApiDefinition)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean addApiSpecificMediationPolicy (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, String action)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
APIRevision addAPIRevision (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deployAPIRevision (APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
} }

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.apimgt.extension.rest.api; package io.entgra.device.mgt.core.apimgt.extension.rest.api;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; import io.entgra.device.mgt.core.apimgt.extension.rest.api.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.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
@ -36,14 +37,16 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.ssl.Base64; import org.apache.commons.ssl.Base64;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.*;
import java.io.IOException; import java.io.IOException;
import java.util.List;
public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
private static final Log log = LogFactory.getLog(PublisherRESTAPIServicesImpl.class); private static final Log log = LogFactory.getLog(PublisherRESTAPIServicesImpl.class);
private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder());
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final Gson gson = new Gson();
private static final String host = System.getProperty(Constants.IOT_CORE_HOST); private static final String host = System.getProperty(Constants.IOT_CORE_HOST);
private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT); private static final String port = System.getProperty(Constants.IOT_CORE_HTTPS_PORT);
@ -94,7 +97,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR,
Constants.EMPTY_STRING); Constants.EMPTY_STRING);
String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON String getScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON
+ port + Constants.GET_SCOPE + keyValue; + port + Constants.SCOPE_API_ENDPOINT + keyValue;
Request request = new Request.Builder() Request request = new Request.Builder()
.url(getScopeUrl) .url(getScopeUrl)
@ -117,6 +120,58 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
String msg = "Bad Request, Invalid request"; String msg = "Bad Request, Invalid request";
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} else if (HttpStatus.SC_NOT_FOUND == response.code()) {
String msg = "Shared scope key not found";
log.error(msg);
return false;
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId();
ScopeUtils scopeUtil = new ScopeUtils();
scopeUtil.setKey(scope.getKey());
scopeUtil.setName(scope.getName());
scopeUtil.setDescription(scope.getDescription());
scopeUtil.setRoles(scope.getRoles());
String scopeString = scopeUtil.toJSON();
RequestBody requestBody = RequestBody.create(JSON, scopeString);
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else { } else {
String msg = "Response : " + response.code() + response.body(); String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg); throw new UnexpectedResponseException(msg);
@ -133,7 +188,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
throws APIServicesException, BadRequestException, UnexpectedResponseException { throws APIServicesException, BadRequestException, UnexpectedResponseException {
String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.GET_SCOPE + scope.getId(); + Constants.COLON + port + Constants.SCOPE_API_ENDPOINT + scope.getId();
ScopeUtils scopeUtil = new ScopeUtils(); ScopeUtils scopeUtil = new ScopeUtils();
scopeUtil.setKey(scope.getKey()); scopeUtil.setKey(scope.getKey());
@ -175,4 +230,558 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
throw new APIServicesException(e); throw new APIServicesException(e);
} }
} }
@Override
public API getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApis = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON
+ port + Constants.API_ENDPOINT + apiIdentifier.getUUID();
Request request = new Request.Builder()
.url(getAllApis)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), API.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return getApi(apiApplicationKey, refreshedAccessToken, apiIdentifier);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getAllApis = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host + Constants.COLON
+ port + Constants.GET_ALL_APIS;
Request request = new Request.Builder()
.url(getAllApis)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return getApis(apiApplicationKey, refreshedAccessToken);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid request";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public API createAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT;
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api));
Request request = new Request.Builder()
.url(updateScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
return gson.fromJson(response.body().string(), API.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return createAPI(apiApplicationKey, refreshedAccessToken, api);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, API api)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String updateScopeUrl = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + api.getUuid();
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(api));
Request request = new Request.Builder()
.url(updateScopeUrl)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return updateApi(apiApplicationKey, refreshedAccessToken, api);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, String asyncApiDefinition)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid;
RequestBody requestBody = RequestBody.create(JSON, asyncApiDefinition);
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.put(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return saveAsyncApiDefinition(apiApplicationKey, refreshedAccessToken, uuid, asyncApiDefinition);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + apiIdentifier.getUUID() + "/mediation-policies";
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiIdentifier);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid()
+ "/content";
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation));
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String updateApiSpecificMediationPolicyContentAPI = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid()
+ "/content";
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(mediation));
Request request = new Request.Builder()
.url(updateApiSpecificMediationPolicyContentAPI)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.put(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_CREATED == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, String action)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid
+ "&action=" + action;
RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING);
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return changeLifeCycleStatus(apiApplicationKey, refreshedAccessToken, uuid, action);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public JSONObject getAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getLatestRevisionUUIDEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:true";
Request request = new Request.Builder()
.url(getLatestRevisionUUIDEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return getAPIRevision(apiApplicationKey, refreshedAccessToken, uuid);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public JSONObject getAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String getLatestRevisionUUIDEndPoint = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/deployments";
Request request = new Request.Builder()
.url(getLatestRevisionUUIDEndPoint)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.get()
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return getAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, uuid);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions";
String apiRevisionDescription = "{\n" +
" \"description\":\" " + apiRevision.getDescription() + "\",\n" +
"}";
RequestBody requestBody = RequestBody.create(JSON, apiRevisionDescription);
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return gson.fromJson(response.body().string(), APIRevision.class);
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return addAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
@Override
public boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException {
String addNewScope = Constants.HTTPS_PROTOCOL + Constants.SCHEME_SEPARATOR + host
+ Constants.COLON + port + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId="
+ apiRevisionId;
RequestBody requestBody = RequestBody.create(JSON, String.valueOf(apiRevisionDeploymentList));
Request request = new Request.Builder()
.url(addNewScope)
.addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER
+ accessTokenInfo.getAccess_token())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (HttpStatus.SC_OK == response.code()) {
return true;
} else if (HttpStatus.SC_UNAUTHORIZED == response.code()) {
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
AccessTokenInfo refreshedAccessToken = apiApplicationServices.
generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(),
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
//TODO: max attempt count
return deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId,
apiRevisionDeploymentList);
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Bad Request, Invalid scope object";
log.error(msg);
throw new BadRequestException(msg);
} else {
String msg = "Response : " + response.code() + response.body();
throw new UnexpectedResponseException(msg);
}
} catch (IOException e) {
String msg = "Error occurred while processing the response";
log.error(msg, e);
throw new APIServicesException(e);
}
}
} }

@ -61,7 +61,9 @@ public final class Constants {
public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HOST = "iot.core.host";
public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port";
public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000";
public static final String GET_SCOPE = "/api/am/publisher/v2/scopes/"; public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v2/scopes/";
public static final String API_ENDPOINT = "/api/am/publisher/v2/apis/";
public static final String GET_ALL_APIS = "/api/am/publisher/v2/apis?limit=1000";
} }

@ -0,0 +1,139 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.util;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
/**
* This class represents the api data.
*/
public class APIUtils {
private APIIdentifier id;
private String name;
private String description;
private String context;
private String version;
private String provider;
private String type;
private String lifeCycleStatus;
private String workflowStatus;
private String hasThumbnail;
private String transport;
public APIIdentifier getId() {
return id;
}
public void setId(APIIdentifier id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLifeCycleStatus() {
return lifeCycleStatus;
}
public void setLifeCycleStatus(String lifeCycleStatus) {
this.lifeCycleStatus = lifeCycleStatus;
}
public String getWorkflowStatus() {
return workflowStatus;
}
public void setWorkflowStatus(String workflowStatus) {
this.workflowStatus = workflowStatus;
}
public String getHasThumbnail() {
return hasThumbnail;
}
public void setHasThumbnail(String hasThumbnail) {
this.hasThumbnail = hasThumbnail;
}
public String getTransport() {
return transport;
}
public void setTransport(String transport) {
this.transport = transport;
}
public String toJSON() {
String jsonString = "{\n" +
" \"name\":\" " + name + "\",\n" +
" \"description\":\" " + description + "\",\n" +
" \"context\":\" " + context + " \",\n" +
" \"transport\":[\n" +
" \" " + transport + " \"\n" +
" ]\n" +
"}";
return jsonString;
}
}

@ -100,6 +100,20 @@ public class APIPublisherServiceImpl implements APIPublisherService {
tenants.addAll(config.getTenants().getTenant()); tenants.addAll(config.getTenants().getTenant());
RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getOSGiService(RealmService.class, null); .getOSGiService(RealmService.class, null);
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationKey apiApplicationKey;
AccessTokenInfo accessTokenInfo;
try {
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials();
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) {
String errorMsg = "Error while generating application";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
}
try { try {
boolean tenantFound = false; boolean tenantFound = false;
boolean tenantsLoaded = false; boolean tenantsLoaded = false;
@ -140,25 +154,39 @@ public class APIPublisherServiceImpl implements APIPublisherService {
APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()), APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()),
apiConfig.getName(), apiConfig.getVersion()); apiConfig.getName(), apiConfig.getVersion());
if (!apiProvider.isAPIAvailable(apiIdentifier)) { PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONArray apiList = (JSONArray) publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo).get("list");
boolean apiFound = false;
for (int i = 0; i < apiList.length(); i++) {
JSONObject apiObj = apiList.getJSONObject(i);
if (apiObj.getString("name").equals(apiIdentifier.getApiName())){
apiFound = true;
}
}
if (!apiFound) {
// add new scopes as shared scopes // add new scopes as shared scopes
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain);
for (ApiScope apiScope : apiConfig.getScopes()) { for (ApiScope apiScope : apiConfig.getScopes()) {
if (!allSharedScopeKeys.contains(apiScope.getKey())) { // if (!allSharedScopeKeys.contains(apiScope.getKey())) {
if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) {
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(apiScope.getName()); scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); // apiProvider.addSharedScope(scope, tenantDomain); //add scope
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
API api = getAPI(apiConfig, true); API api = getAPI(apiConfig, true);
api.setId(apiIdentifier); api.setId(apiIdentifier);
API createdAPI = apiProvider.addAPI(api); // API createdAPI = apiProvider.addAPI(api); // add api
API createdAPI = publisherRESTAPIServices.createAPI(apiApplicationKey, accessTokenInfo , api); // add api
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); // apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); //Update Topics of an Async API
publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
api.getUuid(), apiConfig.getAsyncApiDefinition());
} }
if (CREATED_STATUS.equals(createdAPI.getStatus())) { if (CREATED_STATUS.equals(createdAPI.getStatus())) {
// if endpoint type "dynamic" and then add in sequence // if endpoint type "dynamic" and then add in sequence
@ -168,14 +196,20 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setConfig(apiConfig.getInSequenceConfig());
mediation.setType("in"); mediation.setType("in");
mediation.setGlobal(false); mediation.setGlobal(false);
apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation, // apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation,
tenantDomain); // tenantDomain); //Update an API Specific Mediation Policy
publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
accessTokenInfo, createdAPI.getUuid(), mediation);
} }
apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); // apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); //Change API Status
publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, createdAPI.getUuid(), PUBLISH_ACTION);
APIRevision apiRevision = new APIRevision(); APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(createdAPI.getUuid()); apiRevision.setApiUUID(createdAPI.getUuid());
apiRevision.setDescription("Initial Revision"); apiRevision.setDescription("Initial Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); // String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); //Create API Revision
String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getRevisionUUID();
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
@ -184,7 +218,9 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>(); List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>();
apiRevisionDeploymentList.add(apiRevisionDeployment); apiRevisionDeploymentList.add(apiRevisionDeployment);
apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); // apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); //Deploy Revision
publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo,
createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList);
} }
} else { } else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
@ -203,12 +239,13 @@ public class APIPublisherServiceImpl implements APIPublisherService {
// 1. add new scopes as shared scopes // 1. add new scopes as shared scopes
// 2. update the API adding scopes for the URI Templates // 2. update the API adding scopes for the URI Templates
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); // Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain); //get all scopes
Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>(); Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>();
for (ApiScope apiScope : apiConfig.getScopes()) { for (ApiScope apiScope : apiConfig.getScopes()) {
// if the scope is not available as shared scope and it is assigned to an API as a local scope // if the scope is not available as shared scope and it is assigned to an API as a local scope
// need remove the local scope and add as a shared scope // need remove the local scope and add as a shared scope
if (!allSharedScopeKeys.contains(apiScope.getKey())) { if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, apiScope.getKey())) {
// if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) {
if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) {
// collect scope to move as shared scopes // collect scope to move as shared scopes
scopesToMoveAsSharedScopes.add(apiScope); scopesToMoveAsSharedScopes.add(apiScope);
@ -219,19 +256,23 @@ public class APIPublisherServiceImpl implements APIPublisherService {
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); // apiProvider.addSharedScope(scope, tenantDomain); //add scope
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
} }
// Get existing API // Get existing API
API existingAPI = apiProvider.getAPI(apiIdentifier); API existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier);
// API existingAPI = apiProvider.getAPI(apiIdentifier);
if (scopesToMoveAsSharedScopes.size() > 0) { if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes // update API to remove local scopes
API api = getAPI(apiConfig, false); API api = getAPI(apiConfig, false);
api.setStatus(existingAPI.getStatus()); api.setStatus(existingAPI.getStatus());
apiProvider.updateAPI(api); // apiProvider.updateAPI(api);
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) { for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope(); Scope scope = new Scope();
@ -239,17 +280,22 @@ public class APIPublisherServiceImpl implements APIPublisherService {
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); // apiProvider.addSharedScope(scope, tenantDomain);
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
existingAPI = apiProvider.getAPI(apiIdentifier); // existingAPI = apiProvider.getAPI(apiIdentifier);
existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo , apiIdentifier);;
API api = getAPI(apiConfig, true); API api = getAPI(apiConfig, true);
api.setStatus(existingAPI.getStatus()); api.setStatus(existingAPI.getStatus());
apiProvider.updateAPI(api); // apiProvider.updateAPI(api);
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); // apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition());
publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
api.getUuid(), apiConfig.getAsyncApiDefinition());
} }
// if endpoint type "dynamic" and then add /update in sequence // if endpoint type "dynamic" and then add /update in sequence
@ -260,35 +306,50 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setType("in"); mediation.setType("in");
mediation.setGlobal(false); mediation.setGlobal(false);
List<Mediation> mediationList = apiProvider // List<Mediation> mediationList = apiProvider
.getAllApiSpecificMediationPolicies(apiIdentifier); // .getAllApiSpecificMediationPolicies(apiIdentifier);
List<Mediation> mediationList = (List) publisherRESTAPIServices
.getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiIdentifier).get("list");
boolean isMediationPolicyFound = false; boolean isMediationPolicyFound = false;
for (Mediation m : mediationList) { for (Mediation m : mediationList) {
if (apiConfig.getInSequenceName().equals(m.getName())) { if (apiConfig.getInSequenceName().equals(m.getName())) {
m.setConfig(apiConfig.getInSequenceConfig()); m.setConfig(apiConfig.getInSequenceConfig());
apiProvider // apiProvider
.updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, // .updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m,
tenantDomain); // tenantDomain);
publisherRESTAPIServices.
updateApiSpecificMediationPolicyContent(apiApplicationKey,
accessTokenInfo, existingAPI.getUuid(), m);
isMediationPolicyFound = true; isMediationPolicyFound = true;
break; break;
} }
} }
if (!isMediationPolicyFound) { if (!isMediationPolicyFound) {
apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation, // apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation,
tenantDomain); // tenantDomain);
publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
accessTokenInfo, existingAPI.getUuid(), mediation);
} }
} }
// Assumption: Assume the latest revision is the published one // Assumption: Assume the latest revision is the published one
String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid());
List<APIRevisionDeployment> latestRevisionDeploymentList = // List<APIRevisionDeployment> latestRevisionDeploymentList =
apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); // apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID);
List<APIRevisionDeployment> latestRevisionDeploymentList = (List<APIRevisionDeployment>)
publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid());
// List<APIRevision> apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid());
List<APIRevision> apiRevisionList = (List<APIRevision>) publisherRESTAPIServices.getAPIRevision(apiApplicationKey,
accessTokenInfo, existingAPI.getUuid()).get("list");
List<APIRevision> apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid());
if (apiRevisionList.size() >= 5) { if (apiRevisionList.size() >= 5) {
String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid());
List<APIRevisionDeployment> earliestRevisionDeploymentList = // List<APIRevisionDeployment> earliestRevisionDeploymentList =
apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); // apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID);
List<APIRevisionDeployment> earliestRevisionDeploymentList = (List<APIRevisionDeployment>)
publisherRESTAPIServices.getAPIRevisionDeployment(apiApplicationKey, accessTokenInfo, existingAPI.getUuid());
apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList); apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList);
apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain);
} }
@ -344,7 +405,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiProvider.addDocumentation(api.getId(), apiDocumentation); apiProvider.addDocumentation(api.getId(), apiDocumentation);
apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent);
} }
} catch (FaultGatewaysException | APIManagementException | IOException e) { } catch (FaultGatewaysException | APIManagementException | IOException | APIServicesException |
BadRequestException | UnexpectedResponseException e) {
String msg = "Error occurred while publishing api"; String msg = "Error occurred while publishing api";
log.error(msg, e); log.error(msg, e);
throw new APIManagerPublisherException(e); throw new APIManagerPublisherException(e);

@ -25,6 +25,20 @@
<version>5.0.26-SNAPSHOT</version> <version>5.0.26-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
</dependency>
</dependencies>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>

Loading…
Cancel
Save