Search in sources :

Example 6 with APIVersionComparator

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

the class APIConsumerImpl method getPaginatedAPIsWithTag.

/**
 * Returns the set of APIs with the given tag from the taggedAPIs Map.
 *
 * @param tag   The name of the tag
 * @param start The starting index of the return result set
 * @param end   The end index of the return result set
 * @return A {@link Map} of APIs(between the given indexes) and the total number indicating all the available
 * APIs count
 * @throws APIManagementException
 */
@Override
public Map<String, Object> getPaginatedAPIsWithTag(String tag, int start, int end, String tenantDomain) throws APIManagementException {
    List<API> apiList = new ArrayList<API>();
    Set<API> resultSet = new TreeSet<API>(new APIVersionComparator());
    Map<String, Object> results = new HashMap<String, Object>();
    Set<API> taggedAPISet = this.getAPIsWithTag(tag, tenantDomain);
    if (taggedAPISet != null) {
        if (taggedAPISet.size() < end) {
            end = taggedAPISet.size();
        }
        int totalLength;
        apiList.addAll(taggedAPISet);
        totalLength = apiList.size();
        if (totalLength <= ((start + end) - 1)) {
            end = totalLength;
        } else {
            end = start + end;
        }
        for (int i = start; i < end; i++) {
            resultSet.add(apiList.get(i));
        }
        results.put("apis", resultSet);
        results.put("length", taggedAPISet.size());
    } else {
        results.put("apis", null);
        results.put("length", 0);
    }
    return results;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject)

Example 7 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 in any of the given LC status array
 *
 * @return Map<String, Object>  API result set with pagination information
 * @throws APIManagementException
 */
@Override
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String[] apiStatus, boolean returnAPITags) 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;
    boolean isMore = false;
    String criteria = APIConstants.LCSTATE_SEARCH_TYPE_KEY;
    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);
        criteria = criteria + APIUtil.getORBasedSearchCriteria(apiStatus);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            if (apiStatus != null && apiStatus.length > 0) {
                List<GovernanceArtifact> genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(criteria), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
                totalLength = PaginationContext.getInstance().getLength();
                if (genericArtifacts == null || genericArtifacts.size() == 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 (GovernanceArtifact artifact : genericArtifacts) {
                    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 all paginated 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) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) 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)

Example 8 with APIVersionComparator

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

the class APIConsumerImpl method filterMultipleVersionedAPIs.

private Map<String, Object> filterMultipleVersionedAPIs(Map<String, Object> searchResults) {
    Object apiObj = searchResults.get("apis");
    ArrayList<Object> apiSet;
    ArrayList<APIProduct> apiProductSet = new ArrayList<>();
    if (apiObj instanceof Set) {
        apiSet = new ArrayList<>(((Set) apiObj));
    } else {
        apiSet = (ArrayList<Object>) apiObj;
    }
    // Store the length of the APIs list with the versioned APIs
    int apiSetLengthWithVersionedApis = apiSet.size();
    int totalLength = Integer.parseInt(searchResults.get("length").toString());
    // filter store results if displayMultipleVersions is set to false
    Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
    if (!displayMultipleVersions) {
        SortedSet<API> resultApis = new TreeSet<API>(new APINameComparator());
        for (Object result : apiSet) {
            if (result instanceof API) {
                resultApis.add((API) result);
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> entry = (Map.Entry<Documentation, API>) result;
                resultApis.add(entry.getValue());
            } else if (result instanceof APIProduct) {
                apiProductSet.add((APIProduct) result);
            }
        }
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        String key;
        // Run the result api list through API version comparator and filter out multiple versions
        for (API api : resultApis) {
            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);
            }
        }
        // filter apiSet
        ArrayList<Object> tempApiSet = new ArrayList<Object>();
        for (Object result : apiSet) {
            API api = null;
            String mapKey;
            API latestAPI;
            if (result instanceof API) {
                api = (API) result;
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(api);
                    }
                }
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> docEntry = (Map.Entry<Documentation, API>) result;
                api = docEntry.getValue();
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(docEntry);
                    }
                }
            }
        }
        // Store the length of the APIs list without the versioned APIs
        int apiSetLengthWithoutVersionedApis = tempApiSet.size();
        apiSet = tempApiSet;
        ArrayList<Object> resultAPIandProductSet = new ArrayList<>();
        resultAPIandProductSet.addAll(apiSet);
        resultAPIandProductSet.addAll(apiProductSet);
        resultAPIandProductSet.sort(new ContentSearchResultNameComparator());
        if (apiObj instanceof Set) {
            searchResults.put("apis", new LinkedHashSet<>(resultAPIandProductSet));
        } else {
            searchResults.put("apis", resultAPIandProductSet);
        }
        searchResults.put("length", totalLength - (apiSetLengthWithVersionedApis - (apiSetLengthWithoutVersionedApis + apiProductSet.size())));
    }
    return searchResults;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) TreeSet(java.util.TreeSet) 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) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 9 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 10 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)

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