Search in sources :

Example 86 with RegistryException

use of org.wso2.carbon.registry.core.exceptions.RegistryException in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedPublishedLightWeightAPIs.

/**
 * The method to get Light Weight APIs to Store view
 * @param tenantDomain tenant domain
 * @param start start limit
 * @param end end limit
 * @return Set<API>  Set of APIs
 * @throws APIManagementException
 */
public Map<String, Object> getAllPaginatedPublishedLightWeightAPIs(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.getLightWeightAPI(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 87 with RegistryException

use of org.wso2.carbon.registry.core.exceptions.RegistryException in project carbon-apimgt by wso2.

the class APIConsumerImpl method searchPaginatedAPIs.

/**
 * Pagination API search based on solr indexing
 *
 * @param registry
 * @param searchTerm
 * @param searchType
 * @return
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIs(Registry registry, String searchTerm, String searchType, int start, int end, boolean limitAttributes) throws APIManagementException {
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    List<API> apiList = new ArrayList<API>();
    searchTerm = searchTerm.trim();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    String criteria = APIConstants.API_OVERVIEW_NAME;
    try {
        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;
        }
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        if (artifactManager != null) {
            if (APIConstants.API_PROVIDER.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_PROVIDER;
                searchTerm = searchTerm.replaceAll("@", "-AT-");
            } else if (APIConstants.API_VERSION_LABEL.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_VERSION;
            } else if (APIConstants.API_CONTEXT.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_CONTEXT;
            } else if (APIConstants.API_DESCRIPTION.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_DESCRIPTION;
            } else if (APIConstants.API_TAG.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_TAG;
            }
            // Create the search attribute map for PUBLISHED APIs
            final String searchValue = searchTerm;
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(criteria, new ArrayList<String>() {

                {
                    add(searchValue);
                }
            });
            boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
            // multiple status. This is because pagination is breaking when we do a another filtering with the API Status
            if (!displayAPIsWithMultipleStatus) {
                listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

                    {
                        add(APIConstants.PUBLISHED);
                    }
                });
            }
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            boolean isFound = true;
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                if (APIConstants.API_OVERVIEW_PROVIDER.equals(criteria)) {
                    genericArtifacts = searchAPIsByOwner(artifactManager, searchValue);
                    if (genericArtifacts == null || genericArtifacts.length == 0) {
                        isFound = false;
                    }
                } else {
                    isFound = false;
                }
            }
            if (!isFound) {
                result.put("apis", apiSet);
                result.put("length", 0);
                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, cannot determine total API count without incurring perf hit
                isMore = true;
                // Remove the additional 1 added earlier when setting max pagination limit
                --totalLength;
            }
            int tempLength = 0;
            for (GenericArtifact artifact : genericArtifacts) {
                String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                if (APIUtil.isAllowDisplayAPIsWithMultipleStatus()) {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                } else {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                }
                // Ensure the APIs returned matches the length, there could be an additional API
                // returned due incrementing the pagination limit when getting from registry
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            apiSet.addAll(apiList);
        }
    } catch (RegistryException e) {
        handleException("Failed to search APIs with type", e);
    }
    result.put("apis", apiSet);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}
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) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) 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) JSONObject(org.json.simple.JSONObject) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 88 with RegistryException

use of org.wso2.carbon.registry.core.exceptions.RegistryException in project carbon-apimgt by wso2.

the class APIConsumerImpl method isCandidateAPI.

private boolean isCandidateAPI(String apiPath, String loggedUsername, GenericArtifactManager artifactManager, int tenantId, boolean showAllAPIs, boolean allowMultipleVersions, String apiOwner, String providerId, Registry registry, Map<String, API> apiCollection) throws UserStoreException, RegistryException, APIManagementException {
    AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
    Comparator<API> versionComparator = new APIVersionComparator();
    Resource resource;
    String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
    boolean checkAuthorized;
    String userNameWithoutDomain = loggedUsername;
    if (!loggedUsername.isEmpty() && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
        String[] nameParts = loggedUsername.split("@");
        userNameWithoutDomain = nameParts[0];
    }
    int loggedInUserTenantDomain = -1;
    if (!StringUtils.isEmpty(loggedUsername)) {
        loggedInUserTenantDomain = APIUtil.getTenantId(loggedUsername);
    }
    if (loggedUsername.isEmpty()) {
        // Anonymous user is viewing.
        checkAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
    } else if (tenantId != loggedInUserTenantDomain) {
        // Cross tenant scenario
        providerId = APIUtil.replaceEmailDomainBack(providerId);
        String[] nameParts = providerId.split("@");
        String provideNameWithoutDomain = nameParts[0];
        checkAuthorized = manager.isUserAuthorized(provideNameWithoutDomain, path, ActionConstants.GET);
    } else {
        // Some user is logged in also user and api provider tenant domain are same.
        checkAuthorized = manager.isUserAuthorized(userNameWithoutDomain, path, ActionConstants.GET);
    }
    String apiArtifactId = null;
    if (checkAuthorized) {
        resource = registry.get(apiPath);
        apiArtifactId = resource.getUUID();
    }
    if (apiArtifactId != null) {
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        // check the API status
        String status = APIUtil.getLcStateFromArtifact(artifact);
        API api = null;
        // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
        if (!showAllAPIs) {
            // then we are only interested in published APIs here...
            if (APIConstants.PUBLISHED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        } else {
            // else we are interested in both deprecated/published APIs here...
            if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
                api = APIUtil.getAPI(artifact);
            }
        }
        if (api != null) {
            String apiVisibility = api.getVisibility();
            if (!StringUtils.isEmpty(apiVisibility) && !APIConstants.API_GLOBAL_VISIBILITY.equalsIgnoreCase(apiVisibility)) {
                String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
                String loginUserDomain = MultitenantUtils.getTenantDomain(loggedUsername);
                if (!StringUtils.isEmpty(providerDomain) && !StringUtils.isEmpty(loginUserDomain) && !providerDomain.equals(loginUserDomain)) {
                    return false;
                }
            }
            // apiOwner is the value coming from front end and compared against the API instance
            if (apiOwner != null && !apiOwner.isEmpty()) {
                if (APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && api.getApiOwner() != null && !api.getApiOwner().isEmpty() && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject remote APIs when local admin user's API selected
                    return false;
                } else if (!APIUtil.replaceEmailDomainBack(providerId).equals(APIUtil.replaceEmailDomainBack(apiOwner)) && !APIUtil.replaceEmailDomainBack(apiOwner).equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    // reject local admin's APIs when remote API selected
                    return false;
                }
            }
            String key;
            // Check the configuration to allow showing multiple versions of an API true/false
            if (!allowMultipleVersions) {
                // If allow only showing the latest version of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                API existingAPI = apiCollection.get(key);
                if (existingAPI != null) {
                    // this one has a higher version number
                    if (versionComparator.compare(api, existingAPI) > 0) {
                        apiCollection.put(key, api);
                        return true;
                    }
                } else {
                    // We haven't seen this API before
                    apiCollection.put(key, api);
                    return true;
                }
            } else {
                // If allow showing multiple versions of an API
                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName() + COLON_CHAR + api.getId().getVersion();
                // we're not really interested in the key, so generate one for the sake of adding this element to
                // the map.
                key = key + '_' + apiCollection.size();
                apiCollection.put(key, api);
                return true;
            }
        }
    }
    return false;
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Resource(org.wso2.carbon.registry.core.Resource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager)

Example 89 with RegistryException

use of org.wso2.carbon.registry.core.exceptions.RegistryException in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedLightWeightAPIsByStatus.

/**
 * 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> getAllPaginatedLightWeightAPIsByStatus(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 = "lcState=";
    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 = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, 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 = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().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
                    isMore = true;
                    // incurring a 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.getLightWeightAPI(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 90 with RegistryException

use of org.wso2.carbon.registry.core.exceptions.RegistryException 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)

Aggregations

RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)235 Resource (org.wso2.carbon.registry.core.Resource)196 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)167 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)145 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)104 Registry (org.wso2.carbon.registry.core.Registry)95 Test (org.junit.Test)81 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)81 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)75 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)70 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)67 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)61 UserStoreException (org.wso2.carbon.user.api.UserStoreException)60 API (org.wso2.carbon.apimgt.api.model.API)58 IOException (java.io.IOException)57 ArrayList (java.util.ArrayList)55 QName (javax.xml.namespace.QName)42 APIResource (org.wso2.carbon.apimgt.api.doc.model.APIResource)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)40 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)40