Skip to content

Commit

Permalink
- fix issue #417
Browse files Browse the repository at this point in the history
  • Loading branch information
rathnapandi committed Sep 19, 2023
1 parent 6a57ef1 commit 3d2bf0e
Show file tree
Hide file tree
Showing 13 changed files with 1,400 additions and 55 deletions.
4 changes: 4 additions & 0 deletions modules/apim-adapter/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency>
<groupId>dev.failsafe</groupId>
<artifactId>failsafe</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,16 @@ public void update(API apiToUpdate, String desiredState, String vhost, boolean e
apiToUpdate.setState(desiredState);
if (desiredState.equals(API.STATE_DELETED)) {
// If an API in state unpublished or pending, also an orgAdmin can delete it
apimAdapter.apiAdapter.deleteAPIProxy(apiToUpdate);
if (apimAdapter.apiAdapter.isFrontendApiExists(apiToUpdate))
apimAdapter.apiAdapter.deleteAPIProxy(apiToUpdate);
// Additionally we need to delete the BE-API
apimAdapter.apiAdapter.deleteBackendAPI(apiToUpdate);
if (apimAdapter.apiAdapter.isBackendApiExists(apiToUpdate))
apimAdapter.apiAdapter.deleteBackendAPI(apiToUpdate);
} else {
apimAdapter.apiAdapter.updateAPIStatus(apiToUpdate, desiredState, vhost);
if (vhost != null && desiredState.equals(API.STATE_UNPUBLISHED)) {
this.updateVHostRequired = true; // Flag to control update of the VHost
}

}
// Take over the status, as it has been updated now
apiToUpdate.setState(desiredState);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import dev.failsafe.Failsafe;
import dev.failsafe.FailsafeException;
import dev.failsafe.RetryPolicy;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
Expand All @@ -48,6 +51,7 @@
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.ZoneId;
import java.util.*;

Expand Down Expand Up @@ -612,12 +616,12 @@ public void deleteBackendAPI(API api) throws AppException {
LOG.debug("Deleting Backend API : {}", api.getApiId());
try {
URI uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(cmd.getApiBasepath() + APIREPO + api.getApiId()).build();

RestAPICall request = new DELRequest(uri);
try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) request.execute()) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 204) {
LOG.error("Error deleting Backend-API using URI: {}. Response-Code: {} Response: {}", uri, statusCode, EntityUtils.toString(httpResponse.getEntity()));
LOG.error("Error deleting Backend-API. Response-Code: {}", statusCode);
Utils.logPayload(LOG, httpResponse);
throw new AppException("Error deleting Backend-API. Response-Code: " + statusCode, ErrorCode.API_MANAGER_COMMUNICATION);
}
}
Expand All @@ -626,6 +630,46 @@ public void deleteBackendAPI(API api) throws AppException {
}
}

public boolean isBackendApiExists(API api) {
LOG.debug("Get Backend API : {}", api.getApiId());
try {
URI uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(cmd.getApiBasepath() + APIREPO + api.getApiId()).build();
RestAPICall request = new GETRequest(uri);
try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) request.execute()) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
LOG.error("Error getting Backend-API Response-Code: {}", statusCode);
Utils.logPayload(LOG, httpResponse);
return false;
}
return true;
}
} catch (Exception e) {
LOG.error("Cannot get Backend-API.", e);
return false;
}
}

public boolean isFrontendApiExists(API api) {
LOG.debug("Get Frontend API : {}", api.getId());
try {
URI uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(cmd.getApiBasepath() + PROXIES + api.getId()).build();
RestAPICall request = new GETRequest(uri);
try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) request.execute()) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 200) {
LOG.error("Error getting Frontend-API Response-Code: {}", statusCode);
Utils.logPayload(LOG, httpResponse);
return false;
}
return true;
}
} catch (Exception e) {
LOG.error("Cannot get Frontend-API.", e);
return false;
}
}

public void publishAPI(API api, String vhost) throws AppException {
if (API.STATE_PUBLISHED.equals(api.getState())) {
LOG.info("API is already published");
Expand Down Expand Up @@ -935,7 +979,62 @@ public boolean upgradeAccessToNewerAPI(API apiToUpgradeAccess, API referenceAPI,
}
}

public void grantClientOrganization(List<Organization> grantAccessToOrgs, API api, boolean allOrgs) throws AppException {
/**
* Polling catalog to make sure the API manager cache is loaded
*
* @param apiId api id
* @param apiName api name
* @return returns true if api found in catalog
* @throws AppException AppException
*/
public boolean pollCatalogForPublishedState(String apiId, String apiName, String apiState) throws AppException {
RetryPolicy<Object> retryPolicy = RetryPolicy.builder()
.abortOn(AppException.class)
.withDelay(Duration.ofSeconds(3))
.withMaxRetries(80)
.build();
try {
return Failsafe.with(retryPolicy).get(() -> checkCatalogForApiPublishedState(apiId, apiName, apiState));
} catch (FailsafeException e) {
LOG.error("Fail to poll catalog", e);
throw (AppException) e.getCause();
}
}

public boolean checkCatalogForApiPublishedState(String apiId, String apiName, String apiState) throws AppException {
if (!apiState.equals("published")) {
LOG.info("Not checking catalog for API state : {}", apiState);
return true;
}
try {
URI uri = new URIBuilder(cmd.getAPIManagerURL()).setPath(cmd.getApiBasepath() + "/discovery/swagger/api/id/" + apiId).build();
RestAPICall restAPICall = new GETRequest(uri);
try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) restAPICall.execute()) {
int statusCode = httpResponse.getStatusLine().getStatusCode();
String response = EntityUtils.toString(httpResponse.getEntity());
if (statusCode != 200) {
LOG.error("API {} not found in API manger catalog", apiName);
if (LOG.isDebugEnabled()) {
LOG.debug("API manager response : {}", response);
}
throw new AppException("API Not found in API Manager catalog", ErrorCode.CANT_CREATE_BE_API);
}
JsonNode jsonNode = mapper.readTree(response);
String state = jsonNode.get("state").textValue();
if (state.equals("published")) {
return true;
}
}
} catch (AppException e) {
throw e;
} catch (Exception e) {
throw new AppException("Unexpected error creating Backend-API based on API-Specification. Error message: " + e.getMessage(), ErrorCode.CANT_CREATE_BE_API, e);
}
return false;
}

public void grantClientOrganization(List<Organization> grantAccessToOrgs, API api, boolean allOrgs) throws
AppException {
StringBuilder formBody;
if (allOrgs) {
formBody = new StringBuilder("action=all_orgs&apiId=" + api.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import com.axway.apim.lib.utils.rest.Console;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -375,7 +377,7 @@ public static String createFileName(String host, String stage, String prefix) th

public static boolean equalsTagMap(TagMap source, TagMap target) {
if (source == target) return true;
if( source == null || target == null)
if (source == null || target == null)
return false;
if (source.size() != target.size()) return false;
for (String tagName : target.keySet()) {
Expand All @@ -387,18 +389,24 @@ public static boolean equalsTagMap(TagMap source, TagMap target) {
return true;
}

public static int handleAppException(Exception e, Logger logger, ErrorCodeMapper errorCodeMapper){
if(e instanceof AppException){
public static int handleAppException(Exception e, Logger logger, ErrorCodeMapper errorCodeMapper) {
if (e instanceof AppException) {
ErrorCode errorCode = ((AppException) e).getError();
if(errorCode == ErrorCode.SUCCESS){
if (errorCode == ErrorCode.SUCCESS) {
return ErrorCode.SUCCESS.getCode();
}else {
} else {
logger.error("Unexpected error :", e);
return errorCodeMapper.getMapedErrorCode(errorCode).getCode();
}
}else {
} else {
logger.error("Unexpected error :", e);
return errorCodeMapper.getMapedErrorCode(ErrorCode.UNXPECTED_ERROR).getCode();
}
}

public static void logPayload(Logger logger, HttpResponse httpResponse) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("APIManager Response : {}", EntityUtils.toString(httpResponse.getEntity()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -480,13 +480,17 @@ public void grantClientOrganization(){
}

@Test
public void upgradeAccessToNewerAPI() {

public void upgradeAccessToNewerAPI() throws AppException {
APIFilter filter = new APIFilter.Builder()
.hasId("e4ded8c8-0a40-4b50-bc13-552fb7209150")
.build();
API api = apiManagerAPIAdapter.getAPI(filter, true);
api.setApplications(new ArrayList<>());
apiManagerAPIAdapter.upgradeAccessToNewerAPI(api, api);
}

@Test
public void loadActualAPI() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.hasId("e4ded8c8-0a40-4b50-bc13-552fb7209150")
.build();
Expand All @@ -496,7 +500,6 @@ public void loadActualAPI() throws IOException {

@Test
public void testTranslateMethodToName() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.translateMethods(APIFilter.METHOD_TRANSLATION.AS_NAME)
.hasId("e4ded8c8-0a40-4b50-bc13-552fb7209150")
Expand All @@ -519,7 +522,6 @@ public void testTranslateMethodToName() throws IOException {

@Test
public void testTranslateMethodToId() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.hasId("e4ded8c8-0a40-4b50-bc13-552fb7209150")
.build();
Expand All @@ -538,7 +540,6 @@ public void testTranslateMethodToId() throws IOException {

@Test
public void testTranslatePolicyToExternalName() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
// Get the API to test with
APIFilter filter = new APIFilter.Builder()
.translatePolicies(APIFilter.POLICY_TRANSLATION.TO_NAME)
Expand All @@ -555,7 +556,6 @@ public void testTranslatePolicyToExternalName() throws IOException {

@Test
public void loadAPIIncludingQuota() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.includeQuotas(true)
.includeClientApplications(true)
Expand All @@ -577,7 +577,6 @@ public void loadAPIIncludingQuota() throws IOException {

@Test
public void loadAPIIncludingClientOrgs() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.includeClientOrganizations(true)
.hasId("e4ded8c8-0a40-4b50-bc13-552fb7209150")
Expand All @@ -591,7 +590,6 @@ public void loadAPIIncludingClientOrgs() throws IOException {

@Test
public void loadAPIIncludingClientApps() throws IOException {
APIManagerAPIAdapter apiManagerAPIAdapter = apiManagerAdapter.apiAdapter;
APIFilter filter = new APIFilter.Builder()
.includeClientApplications(true)
.includeQuotas(true)
Expand All @@ -607,4 +605,49 @@ public void loadAPIIncludingClientApps() throws IOException {
Assert.assertNotNull(api.getApplications().get(0).getAppQuota(), "Subscribed application should have a quota");
}

@Test
public void pollCatalog() throws AppException {
boolean status = apiManagerAPIAdapter.pollCatalogForPublishedState("d90122a7-9f47-420c-85ca-926125ea7bf6", "Test-App-API2-4618", "published");
Assert.assertTrue(status);
}

@Test
public void pollCatalogUnpublished() throws AppException {
boolean status = apiManagerAPIAdapter.pollCatalogForPublishedState("d90122a7-9f47-420c-85ca-926125ea7bf6", "Test-App-API2-4618", "unpublished");
Assert.assertTrue(status);
}

@Test(expectedExceptions = AppException.class)
public void pollCatalogException() throws AppException {
boolean status = apiManagerAPIAdapter.pollCatalogForPublishedState("d90122a7-9f47-420c-85ca-926125ea7bf6-invalid", "Test-App-API2-4618", "published");
Assert.assertFalse(status);
}

@Test
public void isBackendApiExists(){
API api = new API();
api.setApiId("1f4263ca-7f03-41d9-9d34-9eff79d29bd8");
Assert.assertTrue(apiManagerAPIAdapter.isBackendApiExists(api));
}
@Test
public void isBackendApiNotExists(){
API api = new API();
api.setApiId("1f4263ca-7f03-41d9-9d34-9eff79d29bd8-not");
Assert.assertFalse(apiManagerAPIAdapter.isBackendApiExists(api));
}

@Test
public void isFrontendApiExists(){
API api = new API();
api.setId("e4ded8c8-0a40-4b50-bc13-552fb7209150");
Assert.assertTrue(apiManagerAPIAdapter.isFrontendApiExists(api));
}
@Test
public void isFrontendApiNotExists(){
API api = new API();
api.setId("e4ded8c8-0a40-4b50-bc13-552fb7209150-not");
Assert.assertFalse(apiManagerAPIAdapter.isFrontendApiExists(api));
}


}
Loading

0 comments on commit 3d2bf0e

Please sign in to comment.