Search in sources :

Example 61 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class CommonMappingUtil method getPaginationDTO.

/**
 * Retreives a pagination DTO object given
 *
 * @param limit limit value
 * @param offset offset value (starting position)
 * @param total total number of resources available
 * @param next link to the next page
 * @param previous link to the previous page
 * @return a pagination DTO object given above properties
 */
public static PaginationDTO getPaginationDTO(int limit, int offset, int total, String next, String previous) {
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setLimit(limit);
    paginationDTO.setOffset(offset);
    paginationDTO.setTotal(total);
    paginationDTO.setNext(next);
    paginationDTO.setPrevious(previous);
    return paginationDTO;
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO)

Example 62 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class SearchResultMappingUtil method setPaginationParams.

/**
 * Sets pagination urls for a SearchResultListDTO object given pagination parameters and url parameters
 *
 * @param resultListDTO a SearchResultListDTO object
 * @param query      search condition
 * @param limit      max number of objects returned
 * @param offset     starting index
 * @param size       max offset
 */
public static void setPaginationParams(SearchResultListDTO resultListDTO, String query, int offset, int limit, int size) {
    // acquiring pagination parameters and setting pagination urls
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
    String paginatedPrevious = "";
    String paginatedNext = "";
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
    }
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setOffset(offset);
    paginationDTO.setLimit(limit);
    paginationDTO.setTotal(size);
    paginationDTO.setNext(paginatedNext);
    paginationDTO.setPrevious(paginatedPrevious);
    resultListDTO.setPagination(paginationDTO);
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO)

Example 63 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class SubscriptionMappingUtil method setPaginationParams.

/**
 * Sets pagination urls for a SubscriptionListDTO object given pagination parameters and url parameters
 *
 * @param subscriptionListDTO a SubscriptionListDTO object
 * @param apiId               uuid/id of API
 * @param groupId             group id of the applications to be returned
 * @param limit               max number of objects returned
 * @param offset              starting index
 * @param size                max offset
 */
public static void setPaginationParams(SubscriptionListDTO subscriptionListDTO, String apiId, String groupId, int limit, int offset, int size) {
    String paginatedPrevious = "";
    String paginatedNext = "";
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = RestApiCommonUtil.getSubscriptionPaginatedURLForAPIId(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), apiId, groupId);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = RestApiCommonUtil.getSubscriptionPaginatedURLForAPIId(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), apiId, groupId);
    }
    PaginationDTO pagination = new PaginationDTO();
    pagination.setOffset(offset);
    pagination.setLimit(limit);
    pagination.setNext(paginatedNext);
    pagination.setPrevious(paginatedPrevious);
    pagination.setTotal(size);
    subscriptionListDTO.setPagination(pagination);
}
Also used : PaginationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO)

Example 64 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class APIConsumerImpl method searchPaginatedAPIs.

@Override
public Map<String, Object> searchPaginatedAPIs(String searchTerm, String searchType, String requestedTenantDomain, int start, int end, boolean isLazyLoad) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    boolean isTenantFlowStarted = false;
    try {
        boolean isTenantMode = (requestedTenantDomain != null);
        if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
        } else {
            requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(requestedTenantDomain, true);
        }
        Registry userRegistry;
        int tenantIDLocal = 0;
        String userNameLocal = this.username;
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {
            // Tenant store anonymous mode
            tenantIDLocal = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(requestedTenantDomain);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
            userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
        } else {
            userRegistry = this.registry;
            tenantIDLocal = tenantId;
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        if (APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX.equalsIgnoreCase(searchType)) {
            Map<Documentation, API> apiDocMap = APIUtil.searchAPIsByDoc(userRegistry, tenantIDLocal, userNameLocal, searchTerm, APIConstants.STORE_CLIENT);
            result.put("apis", apiDocMap);
            /*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
            if (apiDocMap.isEmpty()) {
                result.put("length", 0);
            } else {
                result.put("length", end - start);
            }
        } else {
            result = searchPaginatedAPIs(userRegistry, searchTerm, searchType, start, end, isLazyLoad);
        }
    } catch (Exception e) {
        handleException("Failed to Search APIs", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) 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) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserAdminException(org.wso2.carbon.user.mgt.common.UserAdminException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 65 with Pagination

use of org.wso2.carbon.apimgt.api.model.Pagination in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllPaginatedAPIsByStatus.

/**
 * The method to get APIs by given status to Store view
 *
 * @return Set<API>  Set of APIs
 * @throws APIManagementException
 */
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String apiStatus, boolean returnAPITags) throws APIManagementException {
    try {
        if (tenantDomain != null) {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
    } finally {
        endTenantFlow();
    }
    Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    // Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
    if (APIConstants.PROTOTYPED.equals(apiStatus)) {
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

            {
                add(apiStatus);
            }
        });
    } else {
        if (!displayAPIsWithMultipleStatus) {
            // Create the search attribute map
            listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

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

Aggregations

ArrayList (java.util.ArrayList)20 HashMap (java.util.HashMap)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 JSONObject (org.json.simple.JSONObject)12 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)12 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 PaginationDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO)11 API (org.wso2.carbon.apimgt.api.model.API)10 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)8 PaginationDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO)8 GovernanceArtifact (org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact)8 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)8 TreeSet (java.util.TreeSet)7 Registry (org.wso2.carbon.registry.core.Registry)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 APINameComparator (org.wso2.carbon.apimgt.impl.utils.APINameComparator)6 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)6 UserStoreException (org.wso2.carbon.user.api.UserStoreException)6 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)5