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:mondrian.olap.fun.FunUtil.java

/**
 * Julian's algorithm for stable partial sort. Improves Pedro's algorithm
 * by using a heap (priority queue) for the top {@code limit} items seen.
 * The items on the priority queue have an ordinal field, so the queue
 * can be used to generate a list of stably sorted items. (Heap sort is
 * not normally stable.)//ww w.  ja  va 2 s .  c  om
 *
 * @param list List to sort
 * @param comp Comparator
 * @param limit Maximum number of items to return
 * @param <T> Element type
 * @return Sorted list, containing at most limit items
 */
public static <T> List<T> stablePartialSortJulian(final List<T> list, final Comparator<T> comp, int limit) {
    final Comparator<ObjIntPair<T>> comp2 = new Comparator<ObjIntPair<T>>() {
        public int compare(ObjIntPair<T> o1, ObjIntPair<T> o2) {
            int c = comp.compare(o1.t, o2.t);
            if (c == 0) {
                c = Util.compare(o1.i, o2.i);
            }
            return -c;
        }
    };
    int filled = 0;
    final PriorityQueue<ObjIntPair<T>> queue = new PriorityQueue<ObjIntPair<T>>(limit, comp2);
    for (T element : list) {
        if (filled < limit) {
            queue.offer(new ObjIntPair<T>(element, filled++));
        } else {
            ObjIntPair<T> head = queue.element();
            if (comp.compare(element, head.t) <= 0) {
                ObjIntPair<T> item = new ObjIntPair<T>(element, filled++);
                if (comp2.compare(item, head) >= 0) {
                    ObjIntPair poll = queue.remove();
                    Util.discard(poll);
                    queue.offer(item);
                }
            }
        }
    }

    int n = queue.size();
    final Object[] elements = new Object[n];
    while (n > 0) {
        elements[--n] = queue.poll().t;
    }
    assert queue.isEmpty();
    //noinspection unchecked
    return Arrays.asList((T[]) elements);
}

From source file:mondrian.olap.fun.FunUtil.java

/**
 * Pedro's algorithm for stably sorting the top {@code limit} items in
 * a list./*from   w  ww. j a va 2s . c om*/
 */
public static <T> List<T> stablePartialSortPedro(final List<T> list, final Comparator<T> comp, int limit) {
    final ObjIntPair<T>[] pairs = new ObjIntPair[limit];
    Comparator<ObjIntPair<T>> pairComp = new Comparator<ObjIntPair<T>>() {
        public int compare(ObjIntPair<T> x, ObjIntPair<T> y) {
            int val = comp.compare(x.t, y.t);
            if (val == 0) {
                val = x.i - y.i;
            }
            return val;
        }
    };

    int filled = 0;
    T maximum = null;
    int maximumIndex = 0;
    int originalIndex = 0;
    for (T item : list) { // O(n) to scan list
        switch (filled) {
        case 0:
            maximum = item;
            pairs[0] = new ObjIntPair<T>(item, originalIndex);
            filled++;
            break;
        default:
            if (filled < limit) {
                pairs[filled] = new ObjIntPair<T>(item, originalIndex);

                if (comp.compare(item, maximum) > 0) {
                    maximum = item;
                    maximumIndex = filled;
                }
                filled++;
            } else {
                if (comp.compare(item, maximum) < 0) {
                    pairs[maximumIndex] = new ObjIntPair<T>(item, originalIndex);
                    maximum = pairs[0].t;
                    maximumIndex = 0;
                    for (int i = 0; i < filled; i++) {
                        if (comp.compare(pairs[i].t, maximum) > 0) {
                            maximum = pairs[i].t;
                            maximumIndex = i;
                        }
                    }
                }
            }
        }
        originalIndex++;
    }

    Arrays.sort(pairs, pairComp);

    if (false)
        for (int i = 0; i < limit; i++) {
            T item = pairs[i].t;
            T originalItem = list.get(i);
            int itemIndex = pairs[i].i;
            if (itemIndex < i) {
                if (pairs[itemIndex].i > i) {
                    list.set(pairs[itemIndex].i, originalItem);
                }
            } else {
                list.set(itemIndex, originalItem);
            }
            list.set(i, item);
        }

    List<T> result = new ArrayList<T>(limit);
    for (int i = 0; i < limit; i++) {
        result.add(list.get(pairs[i].i));
    }
    return result;
}

From source file:com.projity.field.Field.java

/**
 * Given a collection, if each elements shares the same value for this
 * field, the value is returned, Otherwise null is returned.
 *
 * @param collection//from   w  w w . ja v a2  s .c om
 * @param useMultipleValue
 *            If true, the default value will be used if no elements or
 *            values differ
 * @return
 */
public Object getCommonValue(Collection collection, boolean useMultipleValue, boolean text) {
    if (collection == null)
        return null;
    Iterator i = collection.iterator();
    Object value = null;
    Object current;
    Object currentValue;
    Comparator comparatorToUse = (text ? ComparableComparator.getInstance() : getComparator());
    while (i.hasNext()) {
        current = i.next();
        if (text)
            currentValue = getText(current, null);
        else
            currentValue = getValue(current, null);
        if (value == null)
            value = currentValue;
        else if (0 != comparatorToUse.compare(currentValue, value)) {
            value = null;
            break;
        }
    }
    if (value == null && useMultipleValue) {
        value = getMultipleValueForType();
    }
    return value;
}

From source file:mondrian.olap.fun.FunUtil.java

/**
 * Marc's original algorithm for stable partial sort of a list.
 * Now superseded by {@link #stablePartialSortJulian}.
 *//* w w w.j a  va  2s . c o  m*/
public static <T> List<T> stablePartialSortMarc(final List<T> list, final Comparator<T> comp, int limit) {
    assert limit >= 0;

    // Load an array of pairs {list-item, list-index}.
    // List-index is a secondary sort key, to give a stable sort.
    // REVIEW Can we use a simple T[], with the index implied?
    // REVIEW When limit is big relative to list size, faster to
    // mergesort. Test for this.
    int n = list.size(); // O(n) to scan list
    @SuppressWarnings({ "unchecked" })
    final ObjIntPair<T>[] pairs = new ObjIntPair[n];

    int i = 0;
    for (T item : list) { // O(n) to scan list
        pairs[i] = new ObjIntPair<T>(item, i);
        ++i;
    }

    Comparator<ObjIntPair<T>> pairComp = new Comparator<ObjIntPair<T>>() {
        public int compare(ObjIntPair<T> x, ObjIntPair<T> y) {
            int val = comp.compare(x.t, y.t);
            if (val == 0) {
                val = x.i - y.i;
            }
            return val;
        }
    };

    final int length = Math.min(limit, n);
    // O(n + limit * log(limit)) to quicksort
    partialSort(pairs, pairComp, length);

    // Use an abstract list to avoid doing a copy. The result is immutable.
    return new AbstractList<T>() {
        @Override
        public T get(int index) {
            return pairs[index].t;
        }

        @Override
        public int size() {
            return length;
        }
    };
}

From source file:org.nuclos.client.main.MainController.java

public List<GenericAction> getGenericActions() {
    List<GenericAction> result = new ArrayList<GenericAction>();

    getFileMenuActions(result);/*from   w  w w  .j av  a  2s  .c  o  m*/
    getAdministrationMenuActions(result);
    getConfigurationMenuActions(result);
    //getHelpMenuActions(result);

    List<GenericAction> sortedResult = new ArrayList<GenericAction>();
    getEntityMenuActions(sortedResult);
    getNucletComponentMenuActions(sortedResult);
    getCustomComponentMenuActions(sortedResult);
    getTasklistMenuActions(sortedResult);

    final Collator collator = Collator.getInstance(Locale.getDefault());
    final Comparator<String[]> arrayCollator = ComparatorUtils.arrayComparator(collator);
    Collections.sort(sortedResult, new Comparator<GenericAction>() {
        @Override
        public int compare(GenericAction p1, GenericAction p2) {
            int cmp = arrayCollator.compare(p1.y.x, p2.y.x);
            if (cmp == 0)
                cmp = collator.compare(p1.y.y.getValue(Action.NAME), p2.y.y.getValue(Action.NAME));
            return cmp;
        }
    });
    result.addAll(sortedResult);

    addSearchFilterActions(result);
    addReportActions(result);
    getWorkspaceChooserController().addGenericActions(result);

    return result;
}

From source file:com.github.lindenb.jvarkit.tools.vcfcmp.VcfCompareCallers.java

@Override
public Collection<Throwable> call() throws Exception {
    htsjdk.samtools.util.IntervalTreeMap<Boolean> capture = null;
    PrintWriter exampleWriter = null;
    XMLStreamWriter exampleOut = null;
    PrintStream pw = null;/*from  w w w. jav a  2  s.c  o m*/
    VcfIterator vcfInputs[] = new VcfIterator[] { null, null };
    VCFHeader headers[] = new VCFHeader[] { null, null };
    final List<String> args = getInputFiles();
    try {
        if (args.size() == 1) {
            LOG.info("Reading from stdin and " + args.get(0));
            vcfInputs[0] = VCFUtils.createVcfIteratorStdin();
            vcfInputs[1] = VCFUtils.createVcfIterator(args.get(0));
        } else if (args.size() == 2) {
            LOG.info("Reading from stdin and " + args.get(0) + " and " + args.get(1));
            vcfInputs[0] = VCFUtils.createVcfIterator(args.get(0));
            vcfInputs[1] = VCFUtils.createVcfIterator(args.get(1));
        } else {
            return wrapException(getMessageBundle("illegal.number.of.arguments"));
        }

        if (super.captureFile != null) {
            LOG.info("Reading " + super.captureFile);
            capture = super.readBedFileAsBooleanIntervalTreeMap(super.captureFile);
        }

        for (int i = 0; i < vcfInputs.length; ++i) {
            headers[i] = vcfInputs[i].getHeader();
        }
        /* dicts */
        final SAMSequenceDictionary dict0 = headers[0].getSequenceDictionary();
        final SAMSequenceDictionary dict1 = headers[1].getSequenceDictionary();
        final Comparator<VariantContext> ctxComparator;
        if (dict0 == null && dict1 == null) {
            ctxComparator = VCFUtils.createChromPosRefComparator();
        } else if (dict0 != null && dict1 != null) {
            if (!SequenceUtil.areSequenceDictionariesEqual(dict0, dict1)) {
                return wrapException(getMessageBundle("not.the.same.sequence.dictionaries"));
            }
            ctxComparator = VCFUtils.createTidPosRefComparator(dict0);
        } else {
            return wrapException(getMessageBundle("not.the.same.sequence.dictionaries"));
        }
        /* samples */
        Set<String> samples0 = new HashSet<>(headers[0].getSampleNamesInOrder());
        Set<String> samples1 = new HashSet<>(headers[1].getSampleNamesInOrder());
        Set<String> samples = new TreeSet<>(samples0);
        samples.retainAll(samples1);

        if (samples.size() != samples0.size() || samples.size() != samples1.size()) {
            LOG.warn("Warning: Not the same samples set. Using intersection of both lists.");
        }
        if (samples.isEmpty()) {
            return wrapException("No common samples");
        }

        Map<String, Counter<Category>> sample2info = new HashMap<String, Counter<Category>>(samples.size());
        for (String sampleName : samples) {
            sample2info.put(sampleName, new Counter<Category>());
        }

        if (super.exampleFile != null) {
            exampleWriter = new PrintWriter(exampleFile, "UTF-8");
            XMLOutputFactory xof = XMLOutputFactory.newFactory();
            exampleOut = xof.createXMLStreamWriter(exampleWriter);
            exampleOut.writeStartDocument("UTF-8", "1.0");
            exampleOut.writeStartElement("compare-callers");
        }

        SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(dict0);
        VariantContext buffer[] = new VariantContext[vcfInputs.length];
        VariantContext prev[] = new VariantContext[vcfInputs.length];
        for (;;) {
            VariantContext smallest = null;
            //refill buffer
            for (int i = 0; i < vcfInputs.length; ++i) {
                if (buffer[i] == null && vcfInputs[i] != null) {
                    if (vcfInputs[i].hasNext()) {
                        buffer[i] = vcfInputs[i].peek();
                        /* check data are sorted */
                        if (prev[i] != null && ctxComparator.compare(prev[i], buffer[i]) > 0) {
                            return wrapException("Input " + (i + 1) + "/2 is not sorted"
                                    + (((i == 0 && dict0 == null) || (i == 1 && dict1 == null))
                                            ? "on chrom/pos/ref"
                                            : "on sequence dictionary")
                                    + ". got\n" + buffer[i] + "\nafter\n" + prev[i]);
                        }
                    } else {
                        vcfInputs[i].close();
                        vcfInputs[i] = null;
                    }
                }

                if (buffer[i] != null) {
                    if (smallest == null || ctxComparator.compare(buffer[i], smallest) < 0) {
                        smallest = buffer[i];
                    }
                }
            }

            if (smallest == null)
                break;

            VariantContext ctx0 = null;
            VariantContext ctx1 = null;
            Interval interval = null;

            if (buffer[0] != null && ctxComparator.compare(buffer[0], smallest) == 0) {
                prev[0] = progress.watch(vcfInputs[0].next());
                ctx0 = prev[0];
                buffer[0] = null;
                interval = new Interval(ctx0.getContig(), ctx0.getStart(), ctx0.getEnd());
            }
            if (buffer[1] != null && ctxComparator.compare(buffer[1], smallest) == 0) {
                prev[1] = progress.watch(vcfInputs[1].next());
                ctx1 = prev[1];
                buffer[1] = null;
                interval = new Interval(ctx1.getContig(), ctx1.getStart(), ctx1.getEnd());
            }
            boolean in_capture = true;
            if (capture != null && interval != null) {
                in_capture = capture.containsOverlapping(interval);
            }

            for (final String sampleName : sample2info.keySet()) {
                final Counter<Category> sampleInfo = sample2info.get(sampleName);
                Genotype g0 = (ctx0 == null ? null : ctx0.getGenotype(sampleName));
                Genotype g1 = (ctx1 == null ? null : ctx1.getGenotype(sampleName));
                if (g0 != null && (g0.isNoCall() || !g0.isAvailable()))
                    g0 = null;
                if (g1 != null && (g1.isNoCall() || !g1.isAvailable()))
                    g1 = null;

                if (g0 == null && g1 == null) {
                    watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.both_missing);
                    continue;
                } else if (g0 != null && g1 == null) {
                    if (!in_capture) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.off_target_only_1);
                        continue;
                    }
                    watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_1);

                    if (ctx0.isIndel()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.unique_to_file_1_indel);
                    } else if (ctx0.isSNP()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.unique_to_file_1_snp);
                    }
                    continue;
                } else if (g0 == null && g1 != null) {
                    if (!in_capture) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.off_target_only_2);
                        continue;
                    }
                    watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.unique_to_file_2);
                    if (ctx1.isIndel()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.unique_to_file_2_indel);
                    } else if (ctx1.isSNP()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.unique_to_file_2_snp);
                    }
                    continue;
                } else {
                    if (!in_capture) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.off_target_both);
                        continue;
                    }
                    watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.common_context);
                    if (ctx0.isIndel() && ctx1.isIndel()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.common_context_indel);
                    } else if (ctx0.isSNP() && ctx1.isSNP()) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.common_context_snp);
                    }

                    if ((ctx0.hasID() && !ctx1.hasID()) || (!ctx0.hasID() && ctx1.hasID())
                            || (ctx0.hasID() && ctx1.hasID() && !ctx0.getID().equals(ctx1.getID()))) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.common_context_discordant_id);
                    }

                    if (g0.sameGenotype(g1)) {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo, Category.called_and_same);

                        if (g0.isHomRef()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_and_same_hom_ref);
                        }
                        if (g0.isHomVar()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_and_same_hom_var);
                        } else if (g0.isHet()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_and_same_het);
                        }
                    } else {
                        watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                Category.called_but_discordant);

                        if (g0.isHom() && g1.isHet()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_but_discordant_hom1_het2);
                        } else if (g0.isHet() && g1.isHom()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_but_discordant_het1_hom2);
                        } else if (g0.isHom() && g1.isHom()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_but_discordant_hom1_hom2);
                        } else if (g0.isHet() && g1.isHet()) {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_but_discordant_het1_het2);
                        } else {
                            watch(exampleOut, ctx0, ctx1, g0, g1, sampleName, sampleInfo,
                                    Category.called_but_discordant_others);
                        }
                    }

                }
            }
        }
        progress.finish();

        pw = openFileOrStdoutAsPrintStream();
        pw.print("#Sample");
        for (Category c : Category.values()) {
            pw.print('\t');
            pw.print(c.name());
        }
        pw.println();
        for (String sample : sample2info.keySet()) {
            Counter<Category> count = sample2info.get(sample);
            pw.print(sample);
            for (Category c : Category.values()) {
                pw.print('\t');
                pw.print(count.count(c));
            }
            pw.println();
            if (pw.checkError())
                break;
        }
        pw.flush();

        if (exampleOut != null) {
            exampleOut.writeEndElement();
            exampleOut.writeEndDocument();
            exampleOut.flush();
            exampleOut.close();
        }
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {
        if (getOutputFile() != null)
            CloserUtil.close(pw);
        CloserUtil.close(exampleWriter);
    }

}

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

/**
 * The method to get APIs to Store view      *
 *
 * @return Set<WebApp>  Set of APIs
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 *//* w  w  w  .j  a  v  a 2  s . co  m*/
public Map<String, Object> getAllPaginatedPublishedAPIs(String tenantDomain, int start, int end)
        throws AppManagementException {

    Boolean displayAPIsWithMultipleStatus = isAllowDisplayAPIsWithMultipleStatus();
    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    //Check the app-manager.xml config file entry <DisplayAllAPIs> value is false
    if (!displayAPIsWithMultipleStatus) {
        //Create the search attribute map
        listMap.put(AppMConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
            {
                add(AppMConstants.PUBLISHED);
            }
        });
    } else {
        return getAllPaginatedAPIs(tenantDomain, start, end);
    }

    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();

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

        GenericArtifactManager artifactManager = AppManagerUtil.getArtifactManager(userRegistry,
                AppMConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;
            }

            for (GenericArtifact artifact : genericArtifacts) {
                // 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.evolveum.midpoint.provisioning.impl.ResourceObjectConverter.java

private PropertyModificationOperation convertToReplace(PropertyDelta<?> propertyDelta,
        PrismObject<ShadowType> currentShadow, QName matchingRuleQName) throws SchemaException {
    if (propertyDelta.isReplace()) {
        // this was probably checked before
        throw new IllegalStateException("PropertyDelta is both ADD/DELETE and REPLACE");
    }/*w  ww .j a va  2  s .c om*/
    // let's extract (parent-less) current values
    PrismProperty<?> currentProperty = currentShadow.findProperty(propertyDelta.getPath());
    Collection<PrismPropertyValue> currentValues = new ArrayList<>();
    if (currentProperty != null) {
        for (PrismPropertyValue currentValue : currentProperty.getValues()) {
            currentValues.add(currentValue.clone());
        }
    }
    final MatchingRule matchingRule;
    if (matchingRuleQName != null) {
        ItemDefinition def = propertyDelta.getDefinition();
        QName typeName;
        if (def != null) {
            typeName = def.getTypeName();
        } else {
            typeName = null; // we'll skip testing rule fitness w.r.t type
        }
        matchingRule = matchingRuleRegistry.getMatchingRule(matchingRuleQName, typeName);
    } else {
        matchingRule = null;
    }
    Comparator comparator = new Comparator<PrismPropertyValue<?>>() {
        @Override
        public int compare(PrismPropertyValue<?> o1, PrismPropertyValue<?> o2) {
            if (o1.equalsComplex(o2, true, false, matchingRule)) {
                return 0;
            } else {
                return 1;
            }
        }
    };
    // add values that have to be added
    if (propertyDelta.isAdd()) {
        for (PrismPropertyValue valueToAdd : propertyDelta.getValuesToAdd()) {
            if (!PrismPropertyValue.containsValue(currentValues, valueToAdd, comparator)) {
                currentValues.add(valueToAdd.clone());
            } else {
                LOGGER.warn("Attempting to add a value of {} that is already present in {}: {}",
                        new Object[] { valueToAdd, propertyDelta.getElementName(), currentValues });
            }
        }
    }
    // remove values that should not be there
    if (propertyDelta.isDelete()) {
        for (PrismPropertyValue valueToDelete : propertyDelta.getValuesToDelete()) {
            Iterator<PrismPropertyValue> iterator = currentValues.iterator();
            boolean found = false;
            while (iterator.hasNext()) {
                PrismPropertyValue pValue = iterator.next();
                LOGGER.trace("Comparing existing {} to about-to-be-deleted {}, matching rule: {}",
                        new Object[] { pValue, valueToDelete, matchingRule });
                if (comparator.compare(pValue, valueToDelete) == 0) {
                    LOGGER.trace("MATCH! compared existing {} to about-to-be-deleted {}", pValue,
                            valueToDelete);
                    iterator.remove();
                    found = true;
                }
            }
            if (!found) {
                LOGGER.warn("Attempting to remove a value of {} that is not in {}: {}",
                        new Object[] { valueToDelete, propertyDelta.getElementName(), currentValues });
            }
        }
    }
    PropertyDelta resultingDelta = new PropertyDelta(propertyDelta.getPath(),
            propertyDelta.getPropertyDefinition(), propertyDelta.getPrismContext());
    resultingDelta.setValuesToReplace(currentValues);
    return new PropertyModificationOperation(resultingDelta);
}

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

/**
 * Returned an WebApp set from a set of registry paths
 *
 * @param registry Registry object from which the APIs retrieving,
 * @param limit    Specifies the number of APIs to add.
 * @param apiPaths Array of WebApp paths.
 * @return Set<WebApp> set of APIs
 * @throws RegistryException/*from   ww w.ja va 2  s  .  c o m*/
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 */
private Set<WebApp> getAPIs(Registry registry, int limit, String[] apiPaths)
        throws RegistryException, AppManagementException, org.wso2.carbon.user.api.UserStoreException {

    SortedSet<WebApp> apiSortedSet = new TreeSet<WebApp>(new APINameComparator());
    SortedSet<WebApp> apiVersionsSortedSet = new TreeSet<WebApp>(new APIVersionComparator());

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

    //Find UUID
    GenericArtifactManager artifactManager = AppManagerUtil.getArtifactManager(registry, AppMConstants.API_KEY);
    for (int a = 0; a < apiPaths.length; a++) {
        Resource resource = registry.get(apiPaths[a]);
        if (resource != null && artifactManager != null) {
            GenericArtifact genericArtifact = artifactManager.getGenericArtifact(resource.getUUID());
            WebApp api = null;
            String status = genericArtifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS);
            //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(genericArtifact, registry);
                }
            } else { // else we are interested in both deprecated/published APIs here...
                if (status.equals(AppMConstants.PUBLISHED) || status.equals(AppMConstants.DEPRECATED)) {
                    api = AppManagerUtil.getAPI(genericArtifact, registry);

                }

            }
            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;
    }

}

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

/**
 * The method to get APIs to Store view      *
 *
 * @return Set<WebApp>  Set of APIs
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 *///w  ww . ja  va 2s .  c  o  m
public Set<WebApp> getAllPublishedAPIs(String tenantDomain) throws AppManagementException {
    SortedSet<WebApp> apiSortedSet = new TreeSet<WebApp>(new APINameComparator());
    SortedSet<WebApp> apiVersionsSortedSet = new TreeSet<WebApp>(new APIVersionComparator());
    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;
        GenericArtifactManager artifactManager = AppManagerUtil.getArtifactManager(userRegistry,
                AppMConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.getAllGenericArtifacts();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                return apiSortedSet;
            }

            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();
            for (GenericArtifact artifact : genericArtifacts) {
                // adding the WebApp provider can mark the latest WebApp .
                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);
                    }
                }
            }
            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 all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    }
    return apiSortedSet;

}