Example usage for java.util Comparator compare

List of usage examples for java.util Comparator compare

Introduction

In this page you can find the example usage for java.util Comparator compare.

Prototype

int compare(T o1, T o2);

Source Link

Document

Compares its two arguments for order.

Usage

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

@Override
public Set<API> getPublishedAPIsByProvider(String providerId, int limit) throws APIManagementException {
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    try {//from   www .j ava 2 s .co  m
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
        String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
        if (associations.length < limit || limit == -1) {
            limit = associations.length;
        }
        for (int i = 0; i < limit; i++) {
            Association association = associations[i];
            String apiPath = association.getDestinationPath();
            Resource resource = registry.get(apiPath);
            String apiArtifactId = resource.getUUID();
            if (apiArtifactId != null) {
                GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
                // check the API status
                String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);

                API api = null;
                //Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
                if (!displayAPIsWithMultipleStatus) {
                    // 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 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) {
                            // If we have already seen an API with the same name, make sure
                            // 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);
                    }
                }
            } else {
                throw new GovernanceException("artifact id is null of " + apiPath);
            }
        }
        if (!displayMultipleVersions) {
            apiSortedSet.addAll(latestPublishedAPIs.values());
            return apiSortedSet;
        } else {
            apiVersionsSortedSet.addAll(multiVersionedAPIs);
            return apiVersionsSortedSet;
        }

    } catch (RegistryException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
    }
    return null;
}

From source file:org.wso2.carbon.appmgt.impl.APIConsumerImpl.java

public Set<WebApp> getPublishedAPIsByProvider(String providerId, String loggedUsername, int limit)
        throws AppManagementException {
    SortedSet<WebApp> apiSortedSet = new TreeSet<WebApp>(new APINameComparator());
    SortedSet<WebApp> apiVersionsSortedSet = new TreeSet<WebApp>(new APIVersionComparator());
    try {/*from  w  w  w .j  a va2s .  c  o m*/
        Map<String, WebApp> latestPublishedAPIs = new HashMap<String, WebApp>();
        List<WebApp> multiVersionedAPIs = new ArrayList<WebApp>();
        Comparator<WebApp> versionComparator = new APIVersionComparator();
        Boolean allowMultipleVersions = isAllowDisplayMultipleVersions();
        Boolean showAllAPIs = isAllowDisplayAPIsWithMultipleStatus();

        String providerDomain = MultitenantUtils
                .getTenantDomain(AppManagerUtil.replaceEmailDomainBack(providerId));
        int id = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(providerDomain);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService()
                .getGovernanceSystemRegistry(id);

        org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance()
                .getRealmService().getTenantUserRealm(id).getAuthorizationManager();

        String providerPath = AppMConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
        GenericArtifactManager artifactManager = AppManagerUtil.getArtifactManager(registry,
                AppMConstants.API_KEY);
        Association[] associations = registry.getAssociations(providerPath, AppMConstants.PROVIDER_ASSOCIATION);
        int publishedAPICount = 0;

        for (Association association1 : associations) {

            if (publishedAPICount >= limit) {
                break;
            }

            Association association = association1;
            String apiPath = association.getDestinationPath();

            Resource resource;
            String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
                    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + apiPath);
            boolean checkAuthorized = false;
            String userNameWithoutDomain = loggedUsername;

            String loggedDomainName = "";
            if (!"".equals(loggedUsername)
                    && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(super.tenantDomain)) {
                String[] nameParts = loggedUsername.split("@");
                loggedDomainName = nameParts[1];
                userNameWithoutDomain = nameParts[0];
            }

            if (loggedUsername.equals("")) {
                // Anonymous user is viewing.
                checkAuthorized = manager.isRoleAuthorized(AppMConstants.ANONYMOUS_ROLE, path,
                        ActionConstants.GET);
            } else {
                // Some user is logged in.
                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 WebApp status
                String status = artifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS);

                WebApp api = null;
                //Check the app-manager.xml config file entry <DisplayAllAPIs> value is false
                if (!showAllAPIs) {
                    // then we are only interested in published APIs here...
                    if (status.equals(AppMConstants.PUBLISHED)) {
                        api = AppManagerUtil.getAPI(artifact);
                        publishedAPICount++;
                    }
                } else { // else we are interested in both deprecated/published APIs here...
                    if (status.equals(AppMConstants.PUBLISHED) || status.equals(AppMConstants.DEPRECATED)) {
                        api = AppManagerUtil.getAPI(artifact);
                        publishedAPICount++;

                    }

                }
                if (api != null) {
                    String key;
                    //Check the configuration to allow showing multiple versions of an WebApp true/false
                    if (!allowMultipleVersions) { //If allow only showing the latest version of an WebApp
                        key = api.getId().getProviderName() + ":" + api.getId().getApiName();
                        WebApp existingAPI = latestPublishedAPIs.get(key);
                        if (existingAPI != null) {
                            // If we have already seen an WebApp with the same name, make sure
                            // this one has a higher version number
                            if (versionComparator.compare(api, existingAPI) > 0) {
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // We haven't seen this WebApp before
                            latestPublishedAPIs.put(key, api);
                        }
                    } else { //If allow showing multiple versions of an WebApp
                        key = api.getId().getProviderName() + ":" + api.getId().getApiName() + ":"
                                + api.getId().getVersion();
                        multiVersionedAPIs.add(api);
                    }
                }
            }
        }
        if (!allowMultipleVersions) {
            for (WebApp api : latestPublishedAPIs.values()) {
                apiSortedSet.add(api);
            }
            return apiSortedSet;
        } else {
            for (WebApp api : multiVersionedAPIs) {
                apiVersionsSortedSet.add(api);
            }
            return apiVersionsSortedSet;
        }

    } catch (RegistryException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    } catch (org.wso2.carbon.user.core.UserStoreException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        handleException("Failed to get Published APIs for provider : " + providerId, e);
        return null;
    }

}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * The method to get APIs by given status to Store view
 *
 * @return Set<API>  Set of APIs/*from www . j a va  2 s .co m*/
 * @throws APIManagementException
 */
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end,
        final String apiStatus, boolean returnAPITags) throws APIManagementException {
    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 = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(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);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // 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 if the config is not specified we go with default functionality and load all
        else {
            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) {
                isMore = true; // More APIs exist so we cannot determine the total API count without incurring a
                // performance hit
                --totalLength; // Remove the additional 1 we added earlier when setting max pagination limit
            }
            int tempLength = 0;
            for (GenericArtifact 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) {
                            // If we have already seen an API with the same name, make sure
                            // 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;
            }
        }
    } 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;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

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;// w  w  w. j  av  a2s. c o m
    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 = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);

        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()))) {
                    return false; // reject remote APIs when local admin user's API selected
                } else if (!APIUtil.replaceEmailDomainBack(providerId)
                        .equals(APIUtil.replaceEmailDomainBack(apiOwner))
                        && !APIUtil.replaceEmailDomainBack(apiOwner)
                                .equals(APIUtil.replaceEmailDomainBack(api.getApiOwner()))) {
                    return false; // reject local admin's APIs when remote API selected
                }
            }
            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) {
                    // If we have already seen an API with the same name, make sure
                    // 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;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * 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//w ww  .  ja v a2 s  .  c  om
 */
@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 = "lcState=";

    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(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);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // 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 if the config is not specified we go with default functionality and load all
        else {
            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(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) {
                    isMore = true; // More APIs exist so we cannot determine the total API count without incurring a
                    // performance hit
                    --totalLength; // Remove the additional 1 we added earlier when setting max pagination limit
                }
                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) {
                                // If we have already seen an API with the same name, make sure
                                // 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;
                }
            }
        }
    } 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;

}

From source file:org.openanzo.glitter.query.SPARQLAlgebra.java

/**
 * Implements the SPARQL LeftJoin operator. (For the SPARQL <tt>OPTIONAL</tt> keyword.)
 * /*  w w  w . j a  va2 s.c  o  m*/
 * @param set1
 *            The left-hand-side of the outer join. See the SPARQL spec. for precise semantics.
 * @param set2
 *            The right-hand-side of the outer join.
 * @param filters
 *            Filters that are scoped to this left join.
 * @return The results of applying the LeftJoin operator.
 */
static public SolutionSet leftJoin(SolutionSet set1, SolutionSet set2, Set<Expression> filters) {
    Comparator<Value> comparator = getComparator(set1, set2);

    if (set1 == null)
        return filterSolutions(set2, filters);
    if (set2 == null)
        return filterSolutions(set1, filters);
    long start = 0;
    boolean isEnabled = RequestAnalysis.getAnalysisLogger().isDebugEnabled();
    if (isEnabled) {
        RequestAnalysis.getAnalysisLogger().debug(LogUtils.GLITTER_MARKER,
                "[glitter_SPARQLAlgebra_startLeftJoin] {}:{}", Integer.toString(set1.size()),
                Integer.toString(set2.size()));
        start = System.currentTimeMillis();
    }
    SolutionSet newSolutions = new CustomCompareSolutionSet.ComparableSolutionList(comparator);
    PatternSolution sol1[] = set1.toArray(new PatternSolution[0]);
    // count1 contains all the variables (& bnodes) in the first (required)
    // solution set. count2 contains all the bindables that appear in the
    // second.
    TreeSet<Bindable> count1 = new TreeSet<Bindable>();
    for (PatternSolution element : sol1) {
        for (Bindable bindable : element.getBoundDomain(true)) {
            count1.add(bindable);
        }
    }

    PatternSolution sol2[] = set2.toArray(new PatternSolution[0]);
    TreeSet<Bindable> count2 = new TreeSet<Bindable>();
    for (PatternSolution element : sol2) {
        for (Bindable bindable : element.getBoundDomain(true)) {
            count2.add(bindable);
        }
    }
    // populate matchSet with all the bindables that are in common
    // between the two solution sets.  Order the Binding names in the matchSet
    TreeSet<Bindable> matchSet = new TreeSet<Bindable>();
    if (count1.size() < count2.size()) {
        for (Bindable bindable : count1) {
            if (count2.contains(bindable))
                matchSet.add(bindable);
        }
    } else {
        for (Bindable bindable : count2) {
            if (count1.contains(bindable)) {
                matchSet.add(bindable);
            }
        }
    }
    Bindable matchedBindables[] = matchSet.toArray(new Bindable[0]);
    //Matt:Sort the solutions in sol1+sol2 based on the ordered matchSet, ie
    //the matchSet is sorted alphabetically by the binding names, so sort the solutions in sol1 + sol2
    //by a progressive alphabetical sort based on the ordered binding names, ie
    //if you have binding "A" and binding "B", the solutions would get ordered first by
    //and alphabetical sort of the Binding "A" values, and when the values of Binding "A" match,
    //alphabetical sort of Biding "B" values.
    //
    //Example:  2 Binding "A" and "B"
    //
    // row 1:  A=adam  B=zebra
    // row 2:  A=charlie b=apple
    // row 3:  A=adam  B=david
    // row 4:  A=zed   B=arrow

    //Sort order would be
    // row 3:  A=adam  B=david   //since adam is alphabetically lower than charlie and zed, and then david is lower than zebra
    // row 1:  A=adam  B=zebra
    // row 2:  A=charlie b=apple //charlie is after adam, and before zed, apple isn't used in sort since there are no other values with a match on A
    // row 4:  A=zed   B=arrow  //zed is after adam and charlie, arrow isn't used in sort since there are no other values with a match on A

    long startSort = 0;
    if (isEnabled) {
        startSort = System.currentTimeMillis();
    }
    Arrays.sort(sol1, 0, sol1.length, new PatternSolutionImpl.SetSolutionComparator(matchSet, comparator));
    if (isEnabled) {
        RequestAnalysis.getAnalysisLogger().debug(LogUtils.GLITTER_MARKER,
                "[glitter_SPARQLAlgebra_leftSortTime] {}",
                Long.toString(System.currentTimeMillis() - startSort));
        startSort = System.currentTimeMillis();
    }
    Arrays.sort(sol2, 0, sol2.length, new PatternSolutionImpl.SetSolutionComparator(matchSet, comparator));
    if (isEnabled) {
        RequestAnalysis.getAnalysisLogger().debug(LogUtils.GLITTER_MARKER,
                "[glitter_SPARQLAlgebra_rightSortTime] {}",
                Long.toString(System.currentTimeMillis() - startSort));
        startSort = System.currentTimeMillis();
    }
    // j is our current starting position for iterating over the optional
    // solutions. we can skip optional solutions p..r if we know that all
    // of them are incompatible with required solutions
    // //Matt:You know they are incompatiable because the sort order of the 2 solution sets is the same
    int j = 0;
    //long start = System.currentTimeMillis();

    for (PatternSolution solution1 : sol1) {
        Bindable sol1Bindables[] = solution1.getBoundDomainArray();
        boolean oneMatch = false;
        boolean done = false;
        //Matt:Since the solutions in the 2 sets are in the same sort order, you know that if
        //you compare solution(k) from the right solution set with solution(i) from the left solution set and solution(k) is
        //lower in the sort order than solution(i), then all the remaining solutions in left solution set will also have a
        //higher sort order than solutions(0-k) in right solution set.
        for (int k = j; k < sol2.length && !done; k++) {
            if (sol1Bindables.length == 0) {
                // the empty solution is the unit / identity solution
                oneMatch = true;
                newSolutions.add(sol2[k]);
            } else {
                // match starts as false; if all the bindings in solution1
                // match bindings in solution2 (i.e. solution1 is compatible
                // with solution2), then match==true.
                //
                // Lee: There seems to be a bug here if the intersection of
                // bindable1 and bindable2 is empty: in this case, solution1 does not get
                // extended by solution2, as it should be. Would this be fixed
                // by defaulting match to true?
                boolean match = true;
                boolean cloned = false;
                PatternSolution solution2 = sol2[k];
                // Map<Bindable, Value> conjunction = new HashMap<Bindable, Value>();
                Bindable bindables2[] = solution2.getBoundDomainArray();
                // we traverse the bindables in these solutions in parallel
                // this counter is our current starting position in the optional bindables
                //Matt:Since the bindables in the 2 arrays are in the same sort order, you know that if
                //you compare bindable(m) from the right array with bindable(l) from the left array and bindable(m) is
                //lower in the sort order than bindable(l), then all the remaining bindable in left array will also have a
                //higher sort order than bindable(0-m) in right array.
                int m = 0;
                // breaker is true if solution1 and solution2 are not compatible;
                // once one non-compatible binding has been found, the rest of
                // the bindables in solution1 will be copied, but we won't bother
                // checking them against solution2.
                boolean breaker = false;
                if (bindables2.length > 0) {
                    for (Bindable element : matchedBindables) {
                        // put in the required solution, unmodified, regardless of whether
                        // we've found any incompatibilities yet
                        //conjunction.put(element, solution1.getBinding(element));
                        for (int mm = m; mm < bindables2.length && !breaker; mm++) {
                            int comp1 = element.compareTo(bindables2[mm]);
                            if (comp1 == 0) {
                                // the same bindable is in both solutions, check
                                // the value its bound to; note that solutions in each
                                // solution set are ordered by comparing terms (bound
                                // values)
                                Value term1 = solution1.getBinding(element);
                                //If term is null, this means that lh solution does not have a binding for a shared binding, so have to do slow conjoin
                                if (term1 == null) {
                                    PatternSolution newSolution = conjoin(solution1, solution2);
                                    if (newSolution != null) {
                                        if (keepSolution(newSolution, filters)) {
                                            // oneMatch indicates that solution1 (from the left-hand side)
                                            // was compatible with at least one solution from the right-hand
                                            // solution set
                                            oneMatch = true;
                                            newSolutions.add(newSolution);
                                        }
                                    }
                                    match = false;
                                    breaker = true;
                                } else {
                                    Value term2 = solution2.getBinding(bindables2[mm]);
                                    int comp = comparator.compare(term1, term2);
                                    if (comp > 0) {
                                        // See note above - since the left solution has
                                        // a higher value for this term, we can skip all
                                        // right-hand solutions before this one when we
                                        // start with the next left-hand solution.
                                        match = false;
                                        breaker = true;
                                        j = k;
                                        break;
                                    } else if (comp < 0) {
                                        match = false;
                                        breaker = true;
                                        done = true;
                                        break;
                                    } else {
                                        if (!cloned) {
                                            bindables2 = bindables2.clone();
                                            cloned = true;
                                        }
                                        match = true;
                                        // conjunction.put(bindables2[mm], term);
                                        bindables2[mm] = null;
                                        m = mm + 1;
                                        break;
                                    }
                                }
                            } else if (comp1 > 0) {
                                m = mm;
                            }
                        }
                    }
                    // match is true if all of the terms in common between solution1
                    // and solution2 are bound to the same value in both solutions
                    if (match) {
                        PatternSolutionImpl newSolution = new PatternSolutionImpl(solution1);
                        // before we accept this conjoined solution, we need to make sure
                        // it passes the filter
                        for (Bindable element : bindables2) {
                            // bindings that match those in solution1 were nulled out above
                            // so if a binding is not null, it extends solution 1 and we copy
                            // it into the conjunction
                            if (element != null) {
                                newSolution.setBinding(element, solution2.getBinding(element));
                            }
                        }
                        if (keepSolution(newSolution, filters)) {
                            // oneMatch indicates that solution1 (from the left-hand side)
                            // was compatible with at least one solution from the right-hand
                            // solution set
                            oneMatch = true;
                            newSolutions.add(newSolution);
                        }
                    }
                }
            }
        }
        // if solution1 wasn't compatible with any solutions in the right-hand side, then we just
        // copy solution1 into our resultset untouched
        if (!oneMatch) {
            newSolutions.add(solution1);
        }
    }
    //System.err.println("LeftJoin:" + (System.currentTimeMillis() - start) + ":" + newSolutions.size());
    if (isEnabled) {
        RequestAnalysis.getAnalysisLogger().debug(LogUtils.GLITTER_MARKER,
                "[glitter_SPARQLAlgebra_endLeftJoin] {}:{}", Integer.toString(newSolutions.size()),
                Long.toString(System.currentTimeMillis() - start));
    }
    return newSolutions;
    /*if (set1 == null)
     return set2;
     if (set2 == null)
     return set1;
     SolutionSet newSolutions = new SolutionList();
     for (PatternSolution ps1 : set1) {
     boolean extendedPs1 = false;
     for (PatternSolution ps2 : set2) {
     PatternSolution psNew = ps1.conjoin(ps2);
     if (psNew != null) {
     extendedPs1 = true;
     newSolutions.add(psNew);
     }
     }
     // for this to be a left  outer join, we have to include the left-hand
     // pattern solution even if all of the right-hand solutions conflict
     // with it
     if (!extendedPs1)
     newSolutions.add(ps1);
     }
     return newSolutions;
     */
}