Search in sources :

Example 11 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIVersionComparatorTest method testProviderNameCompare.

@Test
public void testProviderNameCompare() throws Exception {
    Mockito.when(apiIdentifier1.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier2.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier1.getVersion()).thenReturn(VERSION_1);
    Mockito.when(apiIdentifier2.getVersion()).thenReturn(VERSION_1);
    Mockito.when(apiIdentifier1.getProviderName()).thenReturn(PROVIDER_NAME_1);
    Mockito.when(apiIdentifier2.getProviderName()).thenReturn(PROVIDER_NAME_2);
    APIVersionComparator apiVersionComparator = new APIVersionComparator();
    Assert.assertTrue(apiVersionComparator.compare(api1, api2) < 0);
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) Test(org.junit.Test)

Example 12 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIVersionComparatorTest method testPositiveVersionCompare.

@Test
public void testPositiveVersionCompare() throws Exception {
    Mockito.when(apiIdentifier1.getProviderName()).thenReturn(PROVIDER_NAME_1);
    Mockito.when(apiIdentifier2.getProviderName()).thenReturn(PROVIDER_NAME_1);
    Mockito.when(apiIdentifier1.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier2.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier1.getVersion()).thenReturn(VERSION_2);
    Mockito.when(apiIdentifier2.getVersion()).thenReturn(VERSION_1);
    APIVersionComparator apiVersionComparator = new APIVersionComparator();
    Assert.assertTrue(apiVersionComparator.compare(api1, api2) > 0);
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) Test(org.junit.Test)

Example 13 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIProviderImpl method makeAPIKeysForwardCompatible.

public void makeAPIKeysForwardCompatible(API api) throws APIManagementException {
    String provider = api.getId().getProviderName();
    String apiName = api.getId().getApiName();
    Set<String> versions = getAPIVersions(provider, apiName, api.getOrganization());
    APIVersionComparator comparator = new APIVersionComparator();
    List<API> sortedAPIs = new ArrayList<API>();
    for (String version : versions) {
        if (version.equals(api.getId().getVersion())) {
            continue;
        }
        // getAPI(new APIIdentifier(provider, apiName, version));
        API otherApi = new API(new APIIdentifier(provider, apiName, version));
        if (comparator.compare(otherApi, api) < 0 && !APIConstants.RETIRED.equals(otherApi.getStatus())) {
            sortedAPIs.add(otherApi);
        }
    }
    // Get the subscriptions from the latest api version first
    Collections.sort(sortedAPIs, comparator);
    apiMgtDAO.makeKeysForwardCompatible(new ApiTypeWrapper(api), sortedAPIs);
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 14 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator in project carbon-apimgt by wso2.

the class APIProviderImpl method getOldPublishedAPIList.

/**
 * This method returns a list of previous versions of a given API
 *
 * @param api
 * @return oldPublishedAPIList
 * @throws APIManagementException
 */
private List<APIIdentifier> getOldPublishedAPIList(API api) throws APIManagementException {
    List<APIIdentifier> oldPublishedAPIList = new ArrayList<APIIdentifier>();
    List<API> apiList = getAPIVersionsByProviderAndName(api.getId().getProviderName(), api.getId().getName(), api.getOrganization());
    APIVersionComparator versionComparator = new APIVersionComparator();
    for (API oldAPI : apiList) {
        if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (oldAPI.getStatus().equals(APIConstants.PUBLISHED))) {
            oldPublishedAPIList.add(oldAPI.getId());
        }
    }
    return oldPublishedAPIList;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ArrayList(java.util.ArrayList) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Example 15 with APIVersionComparator

use of org.wso2.carbon.apimgt.impl.utils.APIVersionComparator 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;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Aggregations

APIVersionComparator (org.wso2.carbon.apimgt.impl.utils.APIVersionComparator)19 API (org.wso2.carbon.apimgt.api.model.API)13 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)13 ArrayList (java.util.ArrayList)11 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)10 HashMap (java.util.HashMap)9 TreeSet (java.util.TreeSet)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 JSONObject (org.json.simple.JSONObject)8 APINameComparator (org.wso2.carbon.apimgt.impl.utils.APINameComparator)8 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)7 Registry (org.wso2.carbon.registry.core.Registry)7 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)7 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 Test (org.junit.Test)6 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)6 HashSet (java.util.HashSet)5 LinkedHashSet (java.util.LinkedHashSet)5 List (java.util.List)5