use of org.wso2.carbon.apimgt.impl.utils.APINameComparator in project carbon-apimgt by wso2.
the class APINameComparatorTest method testVersionCompare.
@Test
public void testVersionCompare() throws Exception {
Mockito.when(apiIdentifier1.getApiName()).thenReturn(API_NAME_1);
Mockito.when(apiIdentifier2.getApiName()).thenReturn(API_NAME_1);
Mockito.when(apiIdentifier1.getVersion()).thenReturn(VERSION_1);
Mockito.when(apiIdentifier2.getVersion()).thenReturn(VERSION_2);
APINameComparator apiNameComparator = new APINameComparator();
Assert.assertTrue(apiNameComparator.compare(api1, api2) < 0);
}
use of org.wso2.carbon.apimgt.impl.utils.APINameComparator in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPIsByProvider.
/**
* Get a list of APIs published by the given provider. If a given API has multiple APIs,
* only the latest version will
* be included in this list.
*
* @param providerId , provider id
* @return set of API
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get set of API
*/
@Override
public List<API> getAPIsByProvider(String providerId) throws APIManagementException {
List<API> apiSortedList = new ArrayList<API>();
try {
providerId = APIUtil.replaceEmailDomain(providerId);
String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
for (Association association : associations) {
String apiPath = association.getDestinationPath();
if (registry.resourceExists(apiPath)) {
Resource resource = registry.get(apiPath);
String apiArtifactId = resource.getUUID();
if (apiArtifactId != null) {
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactId);
if (apiArtifact != null) {
String type = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
if (!APIConstants.API_PRODUCT.equals(type)) {
apiSortedList.add(getAPI(apiArtifact));
}
}
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
}
}
} catch (RegistryException e) {
handleException("Failed to get APIs for provider : " + providerId, e);
}
Collections.sort(apiSortedList, new APINameComparator());
return apiSortedList;
}
use of org.wso2.carbon.apimgt.impl.utils.APINameComparator in project carbon-apimgt by wso2.
the class APIProviderImpl method getAllPaginatedAPIs.
@Override
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
Map<String, Object> result = new HashMap<String, Object>();
List<API> apiSortedList = new ArrayList<API>();
int totalLength = 0;
boolean isTenantFlowStarted = false;
try {
String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_PUBLISHER_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
} else // Else if the config is not specifed we go with default functionality and load all
{
maxPaginationLimit = Integer.MAX_VALUE;
}
Registry userRegistry;
boolean isTenantMode = (tenantDomain != null);
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
isTenantFlowStarted = true;
}
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
APIUtil.loadTenantRegistry(tenantId);
userRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
} else {
userRegistry = registry;
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
}
PaginationContext.init(start, end, "ASC", APIConstants.PROVIDER_OVERVIEW_NAME, maxPaginationLimit);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
if (artifactManager != null) {
List<GovernanceArtifact> genericArtifacts = null;
if (isAccessControlRestrictionEnabled && !APIUtil.hasPermission(userNameWithoutChange, APIConstants.Permissions.APIM_ADMIN)) {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getUserRoleListQuery(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
} else {
genericArtifacts = GovernanceUtils.findGovernanceArtifacts(new HashMap<String, List<String>>(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
}
totalLength = PaginationContext.getInstance().getLength();
if (genericArtifacts == null || genericArtifacts.isEmpty()) {
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// performance hit
// Remove the additional 1 we added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GovernanceArtifact artifact : genericArtifacts) {
API api = APIUtil.getAPI(artifact);
if (api != null) {
apiSortedList.add(api);
}
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
Collections.sort(apiSortedList, new APINameComparator());
} else {
String errorMessage = "Failed to retrieve artifact manager when getting paginated APIs of tenant " + tenantDomain;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
} catch (RegistryException e) {
handleException("Failed to get all APIs", e);
} catch (UserStoreException e) {
handleException("Failed to get all APIs", e);
} finally {
PaginationContext.destroy();
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
result.put("apis", apiSortedList);
result.put("totalLength", totalLength);
return result;
}
use of org.wso2.carbon.apimgt.impl.utils.APINameComparator in project carbon-apimgt by wso2.
the class AbstractAPIManager method getAllAPIs.
public List<API> getAllAPIs() throws APIManagementException {
List<API> apiSortedList = new ArrayList<API>();
Organization org = new Organization(tenantDomain);
String[] roles = APIUtil.getFilteredUserRoles(username);
Map<String, Object> properties = APIUtil.getUserProperties(username);
UserContext userCtx = new UserContext(username, org, properties, roles);
try {
PublisherAPISearchResult searchAPIs = apiPersistenceInstance.searchAPIsForPublisher(org, "", 0, Integer.MAX_VALUE, userCtx, null, null);
if (searchAPIs != null) {
List<PublisherAPIInfo> list = searchAPIs.getPublisherAPIInfoList();
for (PublisherAPIInfo publisherAPIInfo : list) {
API mappedAPI = APIMapper.INSTANCE.toApi(publisherAPIInfo);
apiSortedList.add(mappedAPI);
}
}
} catch (APIPersistenceException e) {
throw new APIManagementException("Error while searching the api ", e);
}
Collections.sort(apiSortedList, new APINameComparator());
return apiSortedList;
}
use of org.wso2.carbon.apimgt.impl.utils.APINameComparator in project carbon-apimgt by wso2.
the class APIConsumerImpl method getAllPaginatedAPIsByStatus.
/**
* The method to get APIs by given status to Store view
*
* @return Set<API> Set of APIs
* @throws APIManagementException
*/
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String apiStatus, boolean returnAPITags) throws APIManagementException {
try {
if (tenantDomain != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
} finally {
endTenantFlow();
}
Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
// Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
if (APIConstants.PROTOTYPED.equals(apiStatus)) {
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(apiStatus);
}
});
} else {
if (!displayAPIsWithMultipleStatus) {
// Create the search attribute map
listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
{
add(apiStatus);
}
});
} 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;
boolean isMore = false;
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();
String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
// If the Config exists use it to set the pagination limit
final int maxPaginationLimit;
if (paginationLimit != null) {
// The additional 1 added to the maxPaginationLimit is to help us determine if more
// APIs may exist so that we know that we are unable to determine the actual total
// API count. We will subtract this 1 later on so that it does not interfere with
// the logic of the rest of the application
int pagination = Integer.parseInt(paginationLimit);
// leading to some of the APIs not being displayed
if (pagination < 11) {
pagination = 11;
log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
}
maxPaginationLimit = start + pagination + 1;
} else // Else if the config is not specified we go with default functionality and load all
{
maxPaginationLimit = Integer.MAX_VALUE;
}
PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
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);
result.put("isMore", isMore);
return result;
}
// Check to see if we can speculate that there are more APIs to be loaded
if (maxPaginationLimit == totalLength) {
// More APIs exist so we cannot determine the total API count without incurring a
isMore = true;
// performance hit
// Remove the additional 1 we added earlier when setting max pagination limit
--totalLength;
}
int tempLength = 0;
for (GenericArtifact artifact : genericArtifacts) {
if (artifact == null) {
log.error("Failed to retrieve artifact when getting all paginated APIs by status.");
continue;
}
API api = null;
try {
api = APIUtil.getAPI(artifact);
} catch (APIManagementException e) {
// log and continue since we want to load the rest of the APIs.
log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
}
if (api != null) {
if (returnAPITags) {
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
Set<String> tags = new HashSet<String>();
org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
api.addTags(tags);
}
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);
}
}
tempLength++;
if (tempLength >= totalLength) {
break;
}
}
if (!displayMultipleVersions) {
apiSortedSet.addAll(latestPublishedAPIs.values());
result.put("apis", apiSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
} else {
apiVersionsSortedSet.addAll(multiVersionedAPIs);
result.put("apis", apiVersionsSortedSet);
result.put("totalLength", totalLength);
result.put("isMore", isMore);
return result;
}
} else {
String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving APIs by status.";
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);
result.put("isMore", isMore);
return result;
}
Aggregations