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:VASL.build.module.map.ASLBoardPicker.java

/**
 * Reads the current board directory and constructs the list of available boards
 *///w ww. ja v a 2  s  .c  om
public void refreshPossibleBoards() {
    String files[] = boardDir == null ? new String[0] : boardDir.list();
    List<String> sorted = new ArrayList<String>();
    for (int i = 0; i < files.length; ++i) {
        if (files[i].startsWith("bd") && !(new File(boardDir, files[i])).isDirectory()) {
            String name = files[i].substring(2);
            if (name.endsWith(".gif")) {
                name = name.substring(0, name.indexOf(".gif"));
            } else if (name.indexOf(".") >= 0) {
                name = null;
            }
            if (name != null && !sorted.contains(name)) {
                sorted.add(name);
            }
        }
    }

    //
    // * Strings with leading zeros sort ahead of those without.
    // * Strings with leading integer parts sort ahead of those without.
    // * Strings with lesser leading integer parts sort ahead of those with
    //   greater leading integer parts.
    // * Strings which are otherwise equal are sorted lexicographically by
    //   their trailing noninteger parts.
    //

    final Comparator<Object> alpha = Collator.getInstance();
    final Pattern pat = Pattern.compile("((0*)\\d*)(.*)");

    Comparator<String> comp = new Comparator<String>() {
        public int compare(String o1, String o2) {
            final Matcher m1 = pat.matcher(o1);
            final Matcher m2 = pat.matcher(o2);

            if (!m1.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            if (!m2.matches()) {
                // impossible
                throw new IllegalStateException();
            }

            // count leading zeros
            final int z1 = m1.group(2).length();
            final int z2 = m2.group(2).length();

            // more leading zeros comes first
            if (z1 < z2) {
                return 1;
            } else if (z1 > z2) {
                return -1;
            }

            // same number of leading zeros
            final String o1IntStr = m1.group(1);
            final String o2IntStr = m2.group(1);
            if (o1IntStr.length() > 0) {
                if (o2IntStr.length() > 0) {
                    try {
                        // both strings have integer parts
                        final BigInteger o1Int = new BigInteger(o1IntStr);
                        final BigInteger o2Int = new BigInteger(o2IntStr);

                        if (!o1Int.equals(o2Int)) {
                            // one integer part is smaller than the other
                            return o1Int.compareTo(o2Int);

                        }
                    } catch (NumberFormatException e) {
                        // impossible
                        throw new IllegalStateException(e);
                    }
                } else {
                    // only o1 has an integer part
                    return -1;
                }
            } else if (o2IntStr.length() > 0) {
                // only o2 has an integer part
                return 1;
            }

            // the traling string part is decisive
            return alpha.compare(m1.group(3), m2.group(3));
        }
    };

    Collections.sort(sorted, comp);
    possibleBoards.clear();
    for (int i = 0; i < sorted.size(); ++i) {
        addBoard((String) sorted.get(i));
    }
}

From source file:NavigableMap.java

/**
 * Compare using comparator or natural ordering. Used when the
 * ComparableUsingComparator approach doesn't apply.
 *//*  w  ww.  ja  v  a 2  s.  c o m*/
int compare(K k1, K k2) throws ClassCastException {
    Comparator<? super K> cmp = comparator;
    if (cmp != null)
        return cmp.compare(k1, k2);
    else
        return ((Comparable<K>) k1).compareTo(k2);
}

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

/**
 * Get the recently added APIs set/* www  .  jav  a 2  s  .  c  o m*/
 *
 * @param limit no limit. Return everything else, limit the return list to specified value.
 * @return Set<API>
 * @throws APIManagementException
 */
@Override
public Set<API> getRecentlyAddedAPIs(int limit, String tenantDomain) throws APIManagementException {
    SortedSet<API> recentlyAddedAPIs = new TreeSet<API>(new APINameComparator());
    SortedSet<API> recentlyAddedAPIsWithMultipleVersions = new TreeSet<API>(new APIVersionComparator());
    Registry userRegistry;
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    boolean isRecentlyAddedAPICacheEnabled = Boolean
            .parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE));

    PrivilegedCarbonContext.startTenantFlow();
    boolean isTenantFlowStarted;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        isTenantFlowStarted = true;
    } else {
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        isTenantFlowStarted = true;
    }

    try {
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant based store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
            isTenantFlowStarted = true;
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
            isTenantFlowStarted = true;
        }
        if (isRecentlyAddedAPICacheEnabled) {
            boolean isStatusChanged = false;
            Set<API> recentlyAddedAPI = (Set<API>) Caching
                    .getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                    .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                    .get(username + COLON_CHAR + tenantDomain);
            if (recentlyAddedAPI != null) {
                for (API api : recentlyAddedAPI) {
                    try {
                        if (!APIConstants.PUBLISHED
                                .equalsIgnoreCase(userRegistry.get(APIUtil.getAPIPath(api.getId()))
                                        .getProperty(APIConstants.API_OVERVIEW_STATUS))) {
                            isStatusChanged = true;
                            break;
                        }
                    } catch (Exception ex) {
                        log.error("Error while checking API status for APP " + api.getId().getApiName() + '-'
                                + api.getId().getVersion(), ex);
                    }
                }
                if (!isStatusChanged) {
                    return recentlyAddedAPI;
                }
            }
        }

        PaginationContext.init(0, limit, APIConstants.REGISTRY_ARTIFACT_SEARCH_DESC_ORDER,
                APIConstants.REGISTRY_ARTIFACT_SORT_BY_CREATED_TIME, Integer.MAX_VALUE);
        Map<String, List<String>> listMap = new HashMap<String, List<String>>();
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
            {
                add(APIConstants.PUBLISHED);
            }
        });

        //Find UUID
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            SortedSet<API> allAPIs = new TreeSet<API>(new APINameComparator());
            for (GenericArtifact artifact : genericArtifacts) {

                API api = null;
                try {
                    api = APIUtil.getAPI(artifact);
                } catch (APIManagementException e) {
                    //just log and continue since we want to go through the other APIs as well.
                    log.error("Error loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                }
                if (api != null) {
                    allAPIs.add(api);
                }
            }

            if (!APIUtil.isAllowDisplayMultipleVersions()) {
                Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
                Comparator<API> versionComparator = new APIVersionComparator();
                String key;
                for (API api : allAPIs) {
                    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);
                    }
                }

                recentlyAddedAPIs.addAll(latestPublishedAPIs.values());
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                            .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                            .put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIs;
            } else {
                recentlyAddedAPIsWithMultipleVersions.addAll(allAPIs);
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                            .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                            .put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIsWithMultipleVersions;
            }
        }
    } 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();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return recentlyAddedAPIs;
}

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

/**
 * The method to get All PUBLISHED and DEPRECATED APIs, to Store view      
 *
 * @return Set<WebApp>  Set of APIs
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 *//*from www  . j a  va2s. c  om*/
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end)
        throws AppManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<WebApp> apiSortedSet = new TreeSet<WebApp>(new APINameComparator());
    SortedSet<WebApp> apiVersionsSortedSet = new TreeSet<WebApp>(new APIVersionComparator());
    int totalLength = 0;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            userRegistry = registry;
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);

        Map<String, WebApp> latestPublishedAPIs = new HashMap<String, WebApp>();
        List<WebApp> multiVersionedAPIs = new ArrayList<WebApp>();
        Comparator<WebApp> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = isAllowDisplayMultipleVersions();

        GenericArtifactManager artifactManager = AppManagerUtil.getArtifactManager(userRegistry,
                AppMConstants.API_KEY);

        PaginationContext.init(start, end, "ASC", AppMConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);

        boolean noPublishedAPIs = false;
        if (artifactManager != null) {

            //Create the search attribute map for PUBLISHED APIs
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(AppMConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                {
                    add(AppMConstants.PUBLISHED);
                }
            });

            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                noPublishedAPIs = true;
            }
            int publishedAPICount = 0;
            for (GenericArtifact artifact : genericArtifacts) {
                // adding the WebApp provider can mark the latest WebApp .
                String status = artifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS);

                WebApp api = AppManagerUtil.getAPI(artifact);

                if (api != null) {
                    String key;
                    //Check the configuration to allow showing multiple versions of an WebApp true/false
                    if (!displayMultipleVersions) { //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 (!displayMultipleVersions) {
                publishedAPICount = latestPublishedAPIs.size();
            } else {
                publishedAPICount = multiVersionedAPIs.size();
            }
            if ((start + end) > publishedAPICount) {
                if (publishedAPICount > 0) {
                    /*Starting to retrieve DEPRECATED APIs*/
                    start = 0;
                    /* publishedAPICount is always less than end*/
                    end = end - publishedAPICount;
                } else {
                    start = start - totalLength;
                }
                PaginationContext.init(start, end, "ASC", AppMConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
                //Create the search attribute map for DEPRECATED APIs
                Map<String, List<String>> listMapForDeprecatedAPIs = new HashMap<String, List<String>>();
                listMapForDeprecatedAPIs.put(AppMConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                    {
                        add(AppMConstants.DEPRECATED);
                    }
                });

                GenericArtifact[] genericArtifactsForDeprecatedAPIs = artifactManager
                        .findGenericArtifacts(listMapForDeprecatedAPIs);
                totalLength = totalLength + PaginationContext.getInstance().getLength();
                if ((genericArtifactsForDeprecatedAPIs == null || genericArtifactsForDeprecatedAPIs.length == 0)
                        && noPublishedAPIs) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    return result;
                }

                for (GenericArtifact artifact : genericArtifactsForDeprecatedAPIs) {
                    // adding the WebApp provider can mark the latest WebApp .
                    String status = artifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS);

                    WebApp api = AppManagerUtil.getAPI(artifact);

                    if (api != null) {
                        String key;
                        //Check the configuration to allow showing multiple versions of an WebApp true/false
                        if (!displayMultipleVersions) { //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 (!displayMultipleVersions) {
                for (WebApp api : latestPublishedAPIs.values()) {
                    apiSortedSet.add(api);
                }
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;

            } else {
                for (WebApp api : multiVersionedAPIs) {
                    apiVersionsSortedSet.add(api);
                }
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                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);
    return result;

}

From source file:com.diversityarrays.kdxplore.curate.TrialDataEditor.java

/**
 * Returns into (x,y)OutputValues and the pair of minima for x,y as the
 * result.//ww w.j  a v a2  s.c om
 *
 * @param xSamples
 *            input samples for X
 * @param xValueFactory
 *            value generator for X
 * @param ySamples
 *            input samples for Y
 * @param yValueFactory
 *            value generator for Y
 * @param xOutputValues
 * @param yOutputValues
 * @return an array of the minimums
 */
// TODO use this for plotting data
private Comparable<?>[] collectSampleValuePairsByCurationTableVisibleRowOrder(List<KdxSample> xSamples,
        ValueFactory<?> xValueFactory, List<KdxSample> ySamples, ValueFactory<?> yValueFactory,
        List<Comparable<?>> xOutputValues, List<Comparable<?>> yOutputValues) {

    // The sort order is by the current order of the PlotOrSpecimen-s in the curationTableModel

    // Need to sort by Plot#Specimen

    final Map<String, Integer> viewRowByPosIdent = new HashMap<>();
    for (int vrow = curationTable.getRowCount(); --vrow >= 0;) {
        int mrow = curationTable.convertRowIndexToModel(vrow);
        if (mrow >= 0) {
            PlotOrSpecimen pos = curationTableModel.getPlotOrSpecimenAtRowIndex(mrow);
            String posIdent = InstanceIdentifierUtil.getPlotSpecimenIdentifier(pos);
            viewRowByPosIdent.put(posIdent, vrow);
        }
    }

    Comparator<KdxSample> comparator = new SampleMeasurementComparator(viewRowByPosIdent);
    // First we get both lists in the order specified by the
    // curationTableModel's sort order.
    Collections.sort(xSamples, comparator);
    Collections.sort(ySamples, comparator);

    // List<Pair> values = new ArrayList<Pair>();

    // Next we align each pair of samples - but some may
    // have a missing X and some may have a missing Y.
    // We can only determine this by looking up their respective
    // visible row indices and seeing which one comes first.

    // While one's position (visible row index) is less than
    // the other's - we advance the lesser till we catch up.

    Iterator<KdxSample> xiter = xSamples.iterator();
    Iterator<KdxSample> yiter = ySamples.iterator();

    KdxSample x = xiter.hasNext() ? xiter.next() : null;
    KdxSample y = yiter.hasNext() ? yiter.next() : null;

    Comparable<?> xmin = null;
    Comparable<?> ymin = null;

    while (x != null && y != null) {
        int diff = comparator.compare(x, y);

        Comparable<?> xvalue = null;
        Comparable<?> yvalue = null;
        if (diff < 0) {
            // X is less, advance it after assigning a null Y
            xvalue = xValueFactory.getTraitValue(x);
            x = xiter.hasNext() ? xiter.next() : null;
        } else if (diff == 0) {
            xvalue = xValueFactory.getTraitValue(x);
            x = xiter.hasNext() ? xiter.next() : null;

            yvalue = xValueFactory.getTraitValue(y);
            y = yiter.hasNext() ? yiter.next() : null;
        } else {
            yvalue = xValueFactory.getTraitValue(y);
            y = yiter.hasNext() ? yiter.next() : null;
        }

        xmin = minimumOf(xmin, xvalue);
        ymin = minimumOf(ymin, yvalue);

        xOutputValues.add(xvalue);
        yOutputValues.add(yvalue);
        // values.add(new XYPair(xvalue, yvalue));
    }

    // Only one of these two will activate
    while (y != null) {
        Comparable<?> yvalue = yValueFactory.getTraitValue(y);
        xOutputValues.add(null);
        yOutputValues.add(yvalue);

        // xmin = minimumOf(xmin, xvalue);
        ymin = minimumOf(ymin, yvalue);

        // values.add(new XYPair(null, yvalue));
        y = yiter.hasNext() ? yiter.next() : null;
    }

    while (x != null) {
        Comparable<?> xvalue = xValueFactory.getTraitValue(x);
        xOutputValues.add(xvalue);
        yOutputValues.add(null);

        xmin = minimumOf(xmin, xvalue);
        // ymin = minimumOf(ymin, yvalue);

        // values.add(new XYPair(xvalue, null));
        x = xiter.hasNext() ? xiter.next() : null;
    }

    return new Comparable[] { xmin, ymin };
}

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

public Set<WebApp> getPublishedAPIsByProvider(String providerId, int limit) throws AppManagementException {
    SortedSet<WebApp> apiSortedSet = new TreeSet<WebApp>(new APINameComparator());
    SortedSet<WebApp> apiVersionsSortedSet = new TreeSet<WebApp>(new APIVersionComparator());
    try {//from w ww .  j av a  2  s.c om
        Map<String, WebApp> latestPublishedAPIs = new HashMap<String, WebApp>();
        List<WebApp> multiVersionedAPIs = new ArrayList<WebApp>();
        Comparator<WebApp> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = isAllowDisplayMultipleVersions();
        Boolean displayAPIsWithMultipleStatus = isAllowDisplayAPIsWithMultipleStatus();
        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);
        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 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 (!displayAPIsWithMultipleStatus) {
                    // then we are only interested in published APIs here...
                    if (status.equals(AppMConstants.PUBLISHED)) {
                        api = AppManagerUtil.getAPI(artifact);
                    }
                } else { // else we are interested in both deprecated/published APIs here...
                    if (status.equals(AppMConstants.PUBLISHED) || status.equals(AppMConstants.DEPRECATED)) {
                        api = AppManagerUtil.getAPI(artifact);

                    }

                }
                if (api != null) {
                    String key;
                    //Check the configuration to allow showing multiple versions of an WebApp true/false
                    if (!displayMultipleVersions) { //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);
                    }
                }
            } else {
                throw new GovernanceException("artifact id is null of " + apiPath);
            }
        }
        if (!displayMultipleVersions) {
            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;
    }

}

From source file:gedi.util.ArrayUtils.java

/**
 * Returns the index of the median of the three indexed longs.
 *//*  w w w  . j a  va2s  .  co  m*/
private static <T> int med3(T x[], Comparator<T> comp, int a, int b, int c) {
    return (comp.compare(x[a], x[b]) < 0
            ? (comp.compare(x[b], x[c]) < 0 ? b : comp.compare(x[a], x[c]) < 0 ? c : a)
            : (comp.compare(x[b], x[c]) > 0 ? b : comp.compare(x[a], x[c]) > 0 ? c : a));
}

From source file:gedi.util.ArrayUtils.java

public static <A, K, V> HashMap<K, V> indexSmallest(Iterator<A> it, Function<? super A, ? extends K> toKey,
        Function<? super A, ? extends V> toVal, Comparator<V> takeSmallest) {
    return indexCombine(it, toKey, toVal, (k, vn, vo) -> takeSmallest.compare(vn, vo) <= 0 ? vn : vo);
}

From source file:gedi.util.ArrayUtils.java

public static <T> int unique(T[] a, Comparator<T> comp) {
    if (a.length == 0)
        return 0;
    int index = 0;
    for (int i = 1; i < a.length; i++) {
        if (comp.compare(a[i], a[index]) != 0)
            index++;/*from ww  w. j av a 2  s. c om*/
        a[index] = a[i];
    }
    return index + 1;
}

From source file:gedi.util.ArrayUtils.java

/**
 * Sorts the specified sub-array of longs into ascending order.
 *//*from  w  ww . ja v  a 2 s. c o  m*/
private static <T, P> void sort1(T x[], P[] a2, Comparator<T> comp, int off, int len) {
    // Insertion sort on smallest arrays
    if (len < 7) {
        for (int i = off; i < len + off; i++)
            for (int j = i; j > off && comp.compare(x[j - 1], x[j]) > 0; j--)
                swap(x, a2, j, j - 1);
        return;
    }

    // Choose a partition element, v
    int m = off + (len >> 1); // Small arrays, middle element
    if (len > 7) {
        int l = off;
        int n = off + len - 1;
        if (len > 40) { // Big arrays, pseudomedian of 9
            int s = len / 8;
            l = med3(x, comp, l, l + s, l + 2 * s);
            m = med3(x, comp, m - s, m, m + s);
            n = med3(x, comp, n - 2 * s, n - s, n);
        }
        m = med3(x, comp, l, m, n); // Mid-size, med of 3
    }
    T v = x[m];

    // Establish Invariant: v* (<v)* (>v)* v*
    int a = off, b = a, c = off + len - 1, d = c;
    while (true) {
        while (b <= c && comp.compare(x[b], v) <= 0) {
            if (x[b] == v)
                swap(x, a2, a++, b);
            b++;
        }
        while (c >= b && comp.compare(x[c], v) >= 0) {
            if (x[c] == v)
                swap(x, a2, c, d--);
            c--;
        }
        if (b > c)
            break;
        swap(x, a2, b++, c--);
    }

    // Swap partition elements back to middle
    int s, n = off + len;
    s = Math.min(a - off, b - a);
    vecswap(x, a2, off, b - s, s);
    s = Math.min(d - c, n - d - 1);
    vecswap(x, a2, b, n - s, s);

    // Recursively sort non-partition-elements
    if ((s = b - a) > 1)
        sort1(x, a2, comp, off, s);
    if ((s = d - c) > 1)
        sort1(x, a2, comp, n - s, s);
}