Search in sources :

Example 26 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchContentForDevPortal.

@Override
public DevPortalContentSearchResult searchContentForDevPortal(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    log.debug("Requested query for devportal content search: " + searchQuery);
    Map<String, String> attributes = RegistrySearchUtil.getDevPortalSearchAttributes(searchQuery, ctx, isAllowDisplayAPIsWithMultipleStatus());
    if (log.isDebugEnabled()) {
        log.debug("Search attributes : " + attributes);
    }
    DevPortalContentSearchResult result = null;
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(ctx.getUserame(), org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        String tenantAwareUsername = getTenantAwareUsername(ctx.getUserame());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(tenantAwareUsername);
        GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        int tenantId = holder.getTenantId();
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            throw new APIPersistenceException("Error while searching " + errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        int totalLength = PaginationContext.getInstance().getLength();
        if (resourceData != null) {
            result = new DevPortalContentSearchResult();
            List<SearchContent> contentData = new ArrayList<SearchContent>();
            if (log.isDebugEnabled()) {
                log.debug("Number of records Found: " + resourceData.length);
            }
            for (ResourceData data : resourceData) {
                String resourcePath = data.getResourcePath();
                if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
                    int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
                    resourcePath = resourcePath.substring(index);
                    Resource resource = registry.get(resourcePath);
                    if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
                        if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
                            int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
                            resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
                        }
                        DocumentSearchContent docSearch = new DocumentSearchContent();
                        Resource docResource = registry.get(resourcePath);
                        String docArtifactId = docResource.getUUID();
                        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
                        int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                        String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                        Resource apiResource = registry.get(apiPath);
                        String apiArtifactId = apiResource.getUUID();
                        DevPortalAPI devAPI;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
                            docSearch.setApiName(devAPI.getApiName());
                            docSearch.setApiProvider(devAPI.getProviderName());
                            docSearch.setApiVersion(devAPI.getVersion());
                            docSearch.setApiUUID(devAPI.getId());
                            docSearch.setDocType(doc.getType());
                            docSearch.setId(doc.getId());
                            docSearch.setSourceType(doc.getSourceType());
                            docSearch.setVisibility(doc.getVisibility());
                            docSearch.setName(doc.getName());
                            contentData.add(docSearch);
                        } else {
                            throw new GovernanceException("artifact id is null of " + apiPath);
                        }
                    } else {
                        String apiArtifactId = resource.getUUID();
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            DevPortalAPI devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
                            DevPortalSearchContent content = new DevPortalSearchContent();
                            content.setContext(devAPI.getContext());
                            content.setDescription(devAPI.getDescription());
                            content.setId(devAPI.getId());
                            content.setName(devAPI.getApiName());
                            content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(devAPI.getProviderName()));
                            content.setVersion(devAPI.getVersion());
                            content.setStatus(devAPI.getStatus());
                            content.setBusinessOwner(devAPI.getBusinessOwner());
                            content.setBusinessOwnerEmail(devAPI.getBusinessOwnerEmail());
                            contentData.add(content);
                        } else {
                            throw new GovernanceException("artifact id is null for " + resourcePath);
                        }
                    }
                }
            }
            result.setTotalCount(totalLength);
            result.setReturnedCount(contentData.size());
            result.setResults(contentData);
        }
    } catch (RegistryException | IndexerException | DocumentationPersistenceException e) {
        throw new APIPersistenceException("Error while searching for content ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ArrayList(java.util.ArrayList) DevPortalContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalContentSearchResult) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 27 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method deleteAPI.

@Override
public void deleteAPI(Organization org, String apiId) throws APIPersistenceException {
    boolean transactionCommitted = false;
    boolean tenantFlowStarted = false;
    Registry registry = null;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        registry.beginTransaction();
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        APIIdentifier identifier = new APIIdentifier(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        // Delete the dependencies associated  with the api artifact
        GovernanceArtifact[] dependenciesArray = apiArtifact.getDependencies();
        if (dependenciesArray.length > 0) {
            for (GovernanceArtifact artifact : dependenciesArray) {
                registry.delete(artifact.getPath());
            }
        }
        artifactManager.removeGenericArtifact(apiArtifact);
        String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
        Resource apiResource = registry.get(path);
        String artifactId = apiResource.getUUID();
        artifactManager.removeGenericArtifact(artifactId);
        String thumbPath = RegistryPersistenceUtil.getIconPath(identifier);
        if (registry.resourceExists(thumbPath)) {
            registry.delete(thumbPath);
        }
        String wsdlArchivePath = RegistryPersistenceUtil.getWsdlArchivePath(identifier);
        if (registry.resourceExists(wsdlArchivePath)) {
            registry.delete(wsdlArchivePath);
        }
        /*Remove API Definition Resource - swagger*/
        String apiDefinitionFilePath = APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + '-' + identifier.getVersion() + '-' + identifier.getProviderName();
        if (registry.resourceExists(apiDefinitionFilePath)) {
            registry.delete(apiDefinitionFilePath);
        }
        /*remove empty directories*/
        String apiCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName();
        if (registry.resourceExists(apiCollectionPath)) {
            Resource apiCollection = registry.get(apiCollectionPath);
            CollectionImpl collection = (CollectionImpl) apiCollection;
            // if there is no other versions of apis delete the directory of the api
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more versions of the API found, removing API collection from registry");
                }
                registry.delete(apiCollectionPath);
            }
        }
        String apiProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName();
        if (registry.resourceExists(apiProviderPath)) {
            Resource providerCollection = registry.get(apiProviderPath);
            CollectionImpl collection = (CollectionImpl) providerCollection;
            // if there is no api for given provider delete the provider directory
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more APIs from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
                }
                registry.delete(apiProviderPath);
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
    } catch (RegistryException e) {
        throw new APIPersistenceException("Failed to remove the API : " + apiId, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            throw new APIPersistenceException("Error occurred while rolling back the transaction. ", ex);
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 28 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchAPIsForDevPortal.

@Override
public DevPortalAPISearchResult searchAPIsForDevPortal(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    String requestedTenantDomain = org.getName();
    boolean isTenantFlowStarted = false;
    DevPortalAPISearchResult result = null;
    try {
        RegistryHolder holder = getRegistry(ctx.getUserame(), requestedTenantDomain);
        Registry userRegistry = holder.getRegistry();
        int tenantIDLocal = holder.getTenantId();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        log.debug("Requested query for devportal search: " + searchQuery);
        String modifiedQuery = RegistrySearchUtil.getDevPortalSearchQuery(searchQuery, ctx, isAllowDisplayAPIsWithMultipleStatus(), isAllowDisplayAPIsWithMultipleVersions());
        log.debug("Modified query for devportal search: " + modifiedQuery);
        String userNameLocal;
        if (holder.isAnonymousMode()) {
            userNameLocal = APIConstants.WSO2_ANONYMOUS_USER;
        } else {
            userNameLocal = getTenantAwareUsername(ctx.getUserame());
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        if (searchQuery != null && searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
            result = searchPaginatedDevPortalAPIsByDoc(userRegistry, tenantIDLocal, searchQuery.split(":")[1], userNameLocal, start, offset);
        } else {
            result = searchPaginatedDevPortalAPIs(userRegistry, tenantIDLocal, modifiedQuery, start, offset);
        }
    } catch (APIManagementException e) {
        throw new APIPersistenceException("Error while searching APIs ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) DevPortalAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPISearchResult) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry)

Example 29 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry 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 30 with UserRegistry

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

Aggregations

UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)147 Resource (org.wso2.carbon.registry.core.Resource)96 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)86 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)84 Test (org.junit.Test)75 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)75 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)66 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)65 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)53 API (org.wso2.carbon.apimgt.api.model.API)47 UserStoreException (org.wso2.carbon.user.api.UserStoreException)44 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)43 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)41 Registry (org.wso2.carbon.registry.core.Registry)39 IOException (java.io.IOException)38 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)37 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)34 ArrayList (java.util.ArrayList)33 QName (javax.xml.namespace.QName)32 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)32