Search in sources :

Example 76 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIConsumerImpl method getTopRatedAPIs.

@Override
public Set<API> getTopRatedAPIs(int limit) throws APIManagementException {
    int returnLimit = 0;
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    try {
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when retrieving top rated APIs.";
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact[] genericArtifacts = artifactManager.getAllGenericArtifacts();
        if (genericArtifacts == null || genericArtifacts.length == 0) {
            return apiSortedSet;
        }
        for (GenericArtifact genericArtifact : genericArtifacts) {
            String status = APIUtil.getLcStateFromArtifact(genericArtifact);
            if (APIConstants.PUBLISHED.equals(status)) {
                String artifactPath = genericArtifact.getPath();
                float rating = registry.getAverageRating(artifactPath);
                if (rating > APIConstants.TOP_TATE_MARGIN && (returnLimit < limit)) {
                    returnLimit++;
                    API api = APIUtil.getAPI(genericArtifact, registry);
                    if (api != null) {
                        apiSortedSet.add(api);
                    }
                }
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get top rated API", e);
    }
    return apiSortedSet;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 77 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager 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;
}
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) 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) 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)

Example 78 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager 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;
}
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) 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) 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) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserAdminException(org.wso2.carbon.user.mgt.common.UserAdminException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 79 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIConsumerImpl method getPublishedAPIsByProvider.

@Override
public Set<API> getPublishedAPIsByProvider(String providerId, String loggedUsername, int limit, String apiOwner, String apiBizOwner) throws APIManagementException {
    try {
        Boolean allowMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        Boolean showAllAPIs = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
        String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
        int tenantId = getTenantId(providerDomain);
        final Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when retrieving all published APIs by provider ID " + providerId;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        int publishedAPICount = 0;
        Map<String, API> apiCollection = new HashMap<String, API>();
        if (apiBizOwner != null && !apiBizOwner.isEmpty()) {
            try {
                final String bizOwner = apiBizOwner;
                Map<String, List<String>> listMap = new HashMap<String, List<String>>();
                listMap.put(APIConstants.API_OVERVIEW_BUSS_OWNER, new ArrayList<String>() {

                    {
                        add(bizOwner);
                    }
                });
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
                GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
                if (genericArtifacts != null && genericArtifacts.length > 0) {
                    for (GenericArtifact artifact : genericArtifacts) {
                        if (publishedAPICount >= limit) {
                            break;
                        }
                        if (isCandidateAPI(artifact.getPath(), loggedUsername, artifactManager, tenantId, showAllAPIs, allowMultipleVersions, apiOwner, providerId, registry, apiCollection)) {
                            publishedAPICount += 1;
                        }
                    }
                }
            } catch (GovernanceException e) {
                log.error("Error while finding APIs by business owner " + apiBizOwner, e);
                return null;
            }
        } else {
            String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
            Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
            for (Association association : associations) {
                if (publishedAPICount >= limit) {
                    break;
                }
                String apiPath = association.getDestinationPath();
                if (isCandidateAPI(apiPath, loggedUsername, artifactManager, tenantId, showAllAPIs, allowMultipleVersions, apiOwner, providerId, registry, apiCollection)) {
                    publishedAPICount += 1;
                }
            }
        }
        return new HashSet<API>(apiCollection.values());
    } catch (RegistryException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    } catch (UserStoreException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Association(org.wso2.carbon.registry.core.Association) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 80 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager 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;
}
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) 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) 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)

Aggregations

GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)95 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)90 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)70 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)63 Registry (org.wso2.carbon.registry.core.Registry)57 Resource (org.wso2.carbon.registry.core.Resource)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)51 API (org.wso2.carbon.apimgt.api.model.API)37 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)29 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)29 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)29 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 UserStoreException (org.wso2.carbon.user.api.UserStoreException)27 ArrayList (java.util.ArrayList)26 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)26 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)20 HashMap (java.util.HashMap)18 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)17 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)16