Search in sources :

Example 31 with Tag

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

the class APIConsumerImpl method getAllPaginatedAPIsByStatus.

/**
 * The method to get APIs in any of the given LC status array
 *
 * @return Map<String, Object>  API result set with pagination information
 * @throws APIManagementException
 */
@Override
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String[] apiStatus, boolean returnAPITags) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    boolean isMore = false;
    String criteria = APIConstants.LCSTATE_SEARCH_TYPE_KEY;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn("Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        } else // Else if the config is not specified we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        criteria = criteria + APIUtil.getORBasedSearchCriteria(apiStatus);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            if (apiStatus != null && apiStatus.length > 0) {
                List<GovernanceArtifact> genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(criteria), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
                totalLength = PaginationContext.getInstance().getLength();
                if (genericArtifacts == null || genericArtifacts.size() == 0) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }
                // Check to see if we can speculate that there are more APIs to be loaded
                if (maxPaginationLimit == totalLength) {
                    // More APIs exist so we cannot determine the total API count without incurring a
                    isMore = true;
                    // performance hit
                    // Remove the additional 1 we added earlier when setting max pagination limit
                    --totalLength;
                }
                int tempLength = 0;
                for (GovernanceArtifact artifact : genericArtifacts) {
                    API api = null;
                    try {
                        api = APIUtil.getAPI(artifact);
                    } catch (APIManagementException e) {
                        // log and continue since we want to load the rest of the APIs.
                        log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                    }
                    if (api != null) {
                        if (returnAPITags) {
                            String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
                            Set<String> tags = new HashSet<String>();
                            org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
                            for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
                                tags.add(tag1.getTagName());
                            }
                            api.addTags(tags);
                        }
                        String key;
                        // Check the configuration to allow showing multiple versions of an API true/false
                        if (!displayMultipleVersions) {
                            // If allow only showing the latest version of an API
                            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                            API existingAPI = latestPublishedAPIs.get(key);
                            if (existingAPI != null) {
                                // this one has a higher version number
                                if (versionComparator.compare(api, existingAPI) > 0) {
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // We haven't seen this API before
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // If allow showing multiple versions of an API
                            multiVersionedAPIs.add(api);
                        }
                    }
                    tempLength++;
                    if (tempLength >= totalLength) {
                        break;
                    }
                }
                if (!displayMultipleVersions) {
                    apiSortedSet.addAll(latestPublishedAPIs.values());
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                } else {
                    apiVersionsSortedSet.addAll(multiVersionedAPIs);
                    result.put("apis", apiVersionsSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }
            }
        } else {
            String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all paginated APIs by status.";
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 32 with Tag

use of org.wso2.carbon.registry.core.Tag 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 33 with Tag

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

the class TagMappingUtil method fromTagToDTO.

/**
 * Converts a Tag object into TagDTO
 *
 * @param tag Tag object
 * @return TagDTO corresponds to Tag object
 */
public static TagDTO fromTagToDTO(Tag tag) {
    TagDTO tagDTO = new TagDTO();
    tagDTO.setValue(tag.getName());
    tagDTO.setCount(tag.getNoOfOccurrences());
    return tagDTO;
}
Also used : TagDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.TagDTO)

Example 34 with Tag

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

the class TagsApiServiceImpl method tagsGet.

@Override
public Response tagsGet(Integer limit, Integer offset, String xWSO2Tenant, String ifNoneMatch, MessageContext messageContext) {
    // pre-processing
    limit = limit != null ? limit : RestApiConstants.TAG_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.TAG_OFFSET_DEFAULT;
    Set<Tag> tagSet;
    List<Tag> tagList = new ArrayList<>();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        tagSet = apiConsumer.getAllTags(organization);
        if (tagSet != null) {
            tagList.addAll(tagSet);
        }
        TagListDTO tagListDTO = TagMappingUtil.fromTagListToDTO(tagList, limit, offset);
        TagMappingUtil.setPaginationParams(tagListDTO, limit, offset, tagList.size());
        return Response.ok().entity(tagListDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving tags", e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TagListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.TagListDTO) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.apimgt.api.model.Tag) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 35 with Tag

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

the class TagMappingUtil method fromTagToDTO.

/**
 * Converts a Tag object into TagDTO
 *
 * @param tag Tag object
 * @return TagDTO corresponds to Tag object
 */
public static TagDTO fromTagToDTO(Tag tag) {
    TagDTO tagDTO = new TagDTO();
    tagDTO.setName(tag.getName());
    tagDTO.setWeight(tag.getCount());
    return tagDTO;
}
Also used : TagDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TagDTO)

Aggregations

ArrayList (java.util.ArrayList)21 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)21 Registry (org.wso2.carbon.registry.core.Registry)20 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 Tag (org.wso2.carbon.registry.core.Tag)18 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 API (org.wso2.carbon.apimgt.api.model.API)17 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)16 Resource (org.wso2.carbon.registry.core.Resource)16 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)14 UserStoreException (org.wso2.carbon.user.api.UserStoreException)14 HashSet (java.util.HashSet)13 BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)12 Test (org.junit.Test)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 JSONObject (org.json.simple.JSONObject)10 Tag (org.wso2.carbon.apimgt.api.model.Tag)10 List (java.util.List)9 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)9