Search in sources :

Example 16 with APINameComparator

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);
}
Also used : APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) Test(org.junit.Test)

Example 17 with APINameComparator

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;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Association(org.wso2.carbon.registry.core.Association) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) 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) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 18 with APINameComparator

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;
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONObject(org.json.simple.JSONObject) 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 19 with APINameComparator

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;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject)

Example 20 with APINameComparator

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;
}
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

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