use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedPublishedAPIs.
/**
* The method to get APIs to Store view *
*
* @return Set<API> Set of APIs
* @throws APIManagementException
*/
@Override
@Deprecated
public Map<String, Object> getAllPaginatedPublishedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Boolean displayAPIsWithMultipleStatus = false;
try {
if (tenantDomain != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
} finally {
endTenantFlow();
}
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (!displayAPIsWithMultipleStatus) {
// Create the search attribute map
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
} else {
return getAllPaginatedAPIs(tenantDomain, start, end);
}
Map<String, Object> result = new HashMap<String, Object>();
SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
int totalLength = 0;
try {
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
// Tenant store anonymous mode
int tenantId = getTenantId(tenantDomain);
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(tenantId);
userRegistry = getGovernanceUserRegistry(tenantId);
setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
setUsernameToThreadLocalCarbonContext(this.username);
}
this.isTenantModeStoreView = isTenantMode;
this.requestedTenant = tenantDomain;
Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
List<API> multiVersionedAPIs = new ArrayList<API>();
Comparator<API> versionComparator = new APIVersionComparator();
Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.length == 0) {
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
}
for (GenericArtifact artifact : genericArtifacts) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting paginated published API.");
continue;
}
// adding the API provider can mark the latest API .
API api = APIUtil.getAPI(artifact);
if (api != null) {
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!displayMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
} else {
// If allow showing multiple versions of an API
multiVersionedAPIs.add(api);
}
}
}
if (!displayMultipleVersions) {
apiSortedSet.addAll(latestPublishedAPIs.values());
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
} else {
apiVersionsSortedSet.addAll(multiVersionedAPIs);
result.put("apis", apiVersionsSortedSet);
result.put("totalLength", totalLength);
return result;
}
} else {
String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all Published APIs.";
log.error(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all published APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all published APIs", e);
} finally {
PaginationContext.destroy();
}
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
}
use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.
the class APIConsumerImpl method getRecentlyAddedAPIs.
/**
* Get the recently added APIs set
*
* @param limit no limit. Return everything else, limit the return list to specified value.
* @return Set<API>
* @throws APIManagementException
*/
@Override
public Set<API> getRecentlyAddedAPIs(int limit, String tenantDomain) throws APIManagementException {
SortedSet<API> recentlyAddedAPIs = new TreeSet<API>(new APINameComparator());
SortedSet<API> recentlyAddedAPIsWithMultipleVersions = new TreeSet<API>(new APIVersionComparator());
Registry userRegistry;
APIManagerConfiguration config = getAPIManagerConfiguration();
boolean isRecentlyAddedAPICacheEnabled = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE));
PrivilegedCarbonContext.startTenantFlow();
boolean isTenantFlowStarted;
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
isTenantFlowStarted = true;
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
isTenantFlowStarted = true;
}
try {
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
// Tenant based store anonymous mode
int tenantId = getTenantId(tenantDomain);
// explicitly load the tenant's registry
APIUtil.loadTenantRegistry(tenantId);
setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
isTenantFlowStarted = true;
userRegistry = getGovernanceUserRegistry(tenantId);
} else {
userRegistry = registry;
setUsernameToThreadLocalCarbonContext(this.username);
isTenantFlowStarted = true;
}
if (isRecentlyAddedAPICacheEnabled) {
boolean isStatusChanged = false;
Set<API> recentlyAddedAPI = (Set<API>) Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).get(username + COLON_CHAR + tenantDomain);
if (recentlyAddedAPI != null) {
for (API api : recentlyAddedAPI) {
try {
if (!APIConstants.PUBLISHED.equalsIgnoreCase(userRegistry.get(APIUtil.getAPIPath(api.getId())).getProperty(APIConstants.API_STATUS))) {
isStatusChanged = true;
break;
}
} catch (Exception ex) {
log.error("Error while checking API status for APP " + api.getId().getApiName() + '-' + api.getId().getVersion(), ex);
}
}
if (!isStatusChanged) {
return recentlyAddedAPI;
}
}
}
PaginationContext.init(0, limit, APIConstants.REGISTRY_ARTIFACT_SEARCH_DESC_ORDER, APIConstants.CREATED_DATE, Integer.MAX_VALUE);
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
listMap.put(APIConstants.STORE_VIEW_ROLES, getUserRoleList());
String searchCriteria = APIConstants.LCSTATE_SEARCH_KEY + "= (" + APIConstants.PUBLISHED + ")";
// Find UUID
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
GenericArtifact[] genericArtifacts = artifactManager.findGovernanceArtifacts(getSearchQuery(searchCriteria));
SortedSet<API> allAPIs = new TreeSet<API>(new APINameComparator());
for (GenericArtifact artifact : genericArtifacts) {
API api = null;
try {
api = APIUtil.getAPI(artifact);
} catch (APIManagementException e) {
// just log and continue since we want to go through the other APIs as well.
log.error("Error loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
}
if (api != null) {
allAPIs.add(api);
}
}
if (!APIUtil.isAllowDisplayMultipleVersions()) {
Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
Comparator<API> versionComparator = new APIVersionComparator();
String key;
for (API api : allAPIs) {
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
}
recentlyAddedAPIs.addAll(latestPublishedAPIs.values());
if (isRecentlyAddedAPICacheEnabled) {
Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).put(username + COLON_CHAR + tenantDomain, allAPIs);
}
return recentlyAddedAPIs;
} else {
recentlyAddedAPIsWithMultipleVersions.addAll(allAPIs);
if (isRecentlyAddedAPICacheEnabled) {
Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).put(username + COLON_CHAR + tenantDomain, allAPIs);
}
return recentlyAddedAPIsWithMultipleVersions;
}
} else {
String errorMessage = "Artifact manager is null when retrieving recently added APIs for tenant domain " + tenantDomain;
log.error(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all published APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all published APIs", e);
} finally {
PaginationContext.destroy();
if (isTenantFlowStarted) {
endTenantFlow();
}
}
return recentlyAddedAPIs;
}
use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedAPIs.
/**
* The method to get All PUBLISHED and DEPRECATED APIs, to Store view
*
* @return Set<API> Set of APIs
* @throws APIManagementException
*/
@Deprecated
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Map<String, Object> result = new HashMap<String, Object>();
SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
int totalLength = 0;
try {
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
// Tenant store anonymous mode
int tenantId = getTenantId(tenantDomain);
userRegistry = getGovernanceUserRegistry(tenantId);
setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
setUsernameToThreadLocalCarbonContext(this.username);
}
this.isTenantModeStoreView = isTenantMode;
this.requestedTenant = tenantDomain;
Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
List<API> multiVersionedAPIs = new ArrayList<API>();
Comparator<API> versionComparator = new APIVersionComparator();
Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
boolean noPublishedAPIs = false;
if (artifactManager != null) {
// Create the search attribute map for PUBLISHED APIs
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.length == 0) {
noPublishedAPIs = true;
}
int publishedAPICount;
if (genericArtifacts != null) {
for (GenericArtifact artifact : genericArtifacts) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting all paginated APIs.");
continue;
}
// adding the API provider can mark the latest API .
// String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
API api = APIUtil.getAPI(artifact);
if (api != null) {
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!displayMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
} else {
// If allow showing multiple versions of an API
// key = api.getId().getProviderName() + ":" + api.getId().getApiName() + ":" + api.getId()
// .getVersion();
multiVersionedAPIs.add(api);
}
}
}
}
if (!displayMultipleVersions) {
publishedAPICount = latestPublishedAPIs.size();
} else {
publishedAPICount = multiVersionedAPIs.size();
}
if ((start + end) > publishedAPICount) {
if (publishedAPICount > 0) {
/*Starting to retrieve DEPRECATED APIs*/
start = 0;
/* publishedAPICount is always less than end*/
end = end - publishedAPICount;
} else {
start = start - totalLength;
}
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
// Create the search attribute map for DEPRECATED APIs
Map<String, List<String>> listMapForDeprecatedAPIs = new HashMap<String, List<String>>();
listMapForDeprecatedAPIs.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(APIConstants.DEPRECATED);
}
});
GenericArtifact[] genericArtifactsForDeprecatedAPIs = artifactManager.findGenericArtifacts(listMapForDeprecatedAPIs);
totalLength = totalLength + PaginationContext.getInstance().getLength();
if ((genericArtifactsForDeprecatedAPIs == null || genericArtifactsForDeprecatedAPIs.length == 0) && noPublishedAPIs) {
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
}
if (genericArtifactsForDeprecatedAPIs != null) {
for (GenericArtifact artifact : genericArtifactsForDeprecatedAPIs) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting deprecated APIs.");
continue;
}
// adding the API provider can mark the latest API .
API api = APIUtil.getAPI(artifact);
if (api != null) {
String key;
// Check the configuration to allow showing multiple versions of an API true/false
if (!displayMultipleVersions) {
// If allow only showing the latest version of an API
key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
API existingAPI = latestPublishedAPIs.get(key);
if (existingAPI != null) {
// this one has a higher version number
if (versionComparator.compare(api, existingAPI) > 0) {
latestPublishedAPIs.put(key, api);
}
} else {
// We haven't seen this API before
latestPublishedAPIs.put(key, api);
}
} else {
// If allow showing multiple versions of an API
multiVersionedAPIs.add(api);
}
}
}
}
}
if (!displayMultipleVersions) {
for (API api : latestPublishedAPIs.values()) {
apiSortedSet.add(api);
}
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
} else {
apiVersionsSortedSet.addAll(multiVersionedAPIs);
result.put("apis", apiVersionsSortedSet);
result.put("totalLength", totalLength);
return result;
}
} else {
String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all paginated APIs.";
log.error(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all published APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all published APIs", e);
} finally {
PaginationContext.destroy();
}
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
return result;
}
use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.
the class APIProviderImpl method changeLifeCycle.
private void changeLifeCycle(API api, String currentState, String targetState, Map<String, Boolean> checklist) throws APIManagementException, FaultGatewaysException {
String oldStatus = currentState.toUpperCase();
String newStatus = (targetState != null) ? targetState.toUpperCase() : targetState;
boolean isCurrentCreatedOrPrototyped = APIConstants.CREATED.equals(oldStatus) || APIConstants.PROTOTYPED.equals(oldStatus);
boolean isStateTransitionToPublished = isCurrentCreatedOrPrototyped && APIConstants.PUBLISHED.equals(newStatus);
if (newStatus != null) {
// custom state to default api state
if (isStateTransitionToPublished) {
Set<Tier> tiers = api.getAvailableTiers();
String endPoint = api.getEndpointConfig();
String apiSecurity = api.getApiSecurity();
boolean isOauthProtected = apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2);
if (APIConstants.API_TYPE_WEBSUB.equals(api.getType()) || endPoint != null && endPoint.trim().length() > 0 || api.isAdvertiseOnly() && (api.getApiExternalProductionEndpoint() != null || api.getApiExternalSandboxEndpoint() != null)) {
if ((isOauthProtected && (tiers == null || tiers.size() == 0)) && !api.isAdvertiseOnly()) {
throw new APIManagementException("Failed to publish service to API store. No Tiers selected");
}
} else {
throw new APIManagementException("Failed to publish service to API store. No endpoint selected");
}
}
// push the state change to gateway
Map<String, String> failedGateways = propergateAPIStatusChangeToGateways(newStatus, api);
if (APIConstants.PUBLISHED.equals(newStatus) || !oldStatus.equals(newStatus)) {
// if the API is websocket and if default version is selected, update the other versions
if (APIConstants.APITransportType.WS.toString().equals(api.getType()) && api.isDefaultVersion()) {
Set<String> versions = getAPIVersions(api.getId().getProviderName(), api.getId().getName(), api.getOrganization());
for (String version : versions) {
if (version.equals(api.getId().getVersion())) {
continue;
}
String uuid = APIUtil.getUUIDFromIdentifier(new APIIdentifier(api.getId().getProviderName(), api.getId().getName(), version), api.getOrganization());
API otherApi = getLightweightAPIByUUID(uuid, api.getOrganization());
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, otherApi.getId().getApiName(), otherApi.getId().getId(), otherApi.getUuid(), version, api.getType(), otherApi.getContext(), otherApi.getId().getProviderName(), otherApi.getStatus());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
}
}
if (log.isDebugEnabled()) {
String logMessage = "Publish changed status to the Gateway. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
log.debug(logMessage);
}
// update api related information for state change
updateAPIforStateChange(api, currentState, newStatus);
if (log.isDebugEnabled()) {
String logMessage = "API related information successfully updated. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
log.debug(logMessage);
}
} else {
throw new APIManagementException("Invalid Lifecycle status for default APIExecutor :" + targetState);
}
boolean deprecateOldVersions = false;
boolean makeKeysForwardCompatible = true;
// If the API status is CREATED/PROTOTYPED ,check for check list items of lifecycle
if (isCurrentCreatedOrPrototyped) {
if (checklist != null) {
if (checklist.containsKey(APIConstants.DEPRECATE_CHECK_LIST_ITEM)) {
deprecateOldVersions = checklist.get(APIConstants.DEPRECATE_CHECK_LIST_ITEM);
}
if (checklist.containsKey(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM)) {
makeKeysForwardCompatible = !checklist.get(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM);
}
}
}
if (isStateTransitionToPublished) {
if (makeKeysForwardCompatible) {
makeAPIKeysForwardCompatible(api);
}
if (deprecateOldVersions) {
String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName());
String apiName = api.getId().getName();
List<API> apiList = getAPIVersionsByProviderAndName(provider, apiName, api.getOrganization());
APIVersionComparator versionComparator = new APIVersionComparator();
for (API oldAPI : apiList) {
if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (APIConstants.PUBLISHED.equals(oldAPI.getStatus()))) {
changeLifeCycleStatus(tenantDomain, new ApiTypeWrapper(oldAPI), APIConstants.API_LC_ACTION_DEPRECATE, null);
}
}
}
}
}
Aggregations