Java Examples for java.util.Collections

The following java examples will help you to understand the usage of java.util.Collections. These source code samples are taken from different open source projects.

Example 1
Project: EasyMPermission-master  File: BuilderSingularSets.java View source code
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularSets<T> build() {
    java.util.Set<T> dangerMice;
    switch(((this.dangerMice == null) ? 0 : this.dangerMice.size())) {
        case 0:
            dangerMice = java.util.Collections.emptySet();
            break;
        case 1:
            dangerMice = java.util.Collections.singleton(this.dangerMice.get(0));
            break;
        default:
            dangerMice = new java.util.LinkedHashSet<T>(((this.dangerMice.size() < 0x40000000) ? ((1 + this.dangerMice.size()) + ((this.dangerMice.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            dangerMice.addAll(this.dangerMice);
            dangerMice = java.util.Collections.unmodifiableSet(dangerMice);
    }
    java.util.SortedSet<Number> octopodes = new java.util.TreeSet<Number>();
    if ((this.octopodes != null))
        octopodes.addAll(this.octopodes);
    octopodes = java.util.Collections.unmodifiableSortedSet(octopodes);
    java.util.Set<java.lang.Object> rawSet;
    switch(((this.rawSet == null) ? 0 : this.rawSet.size())) {
        case 0:
            rawSet = java.util.Collections.emptySet();
            break;
        case 1:
            rawSet = java.util.Collections.singleton(this.rawSet.get(0));
            break;
        default:
            rawSet = new java.util.LinkedHashSet<java.lang.Object>(((this.rawSet.size() < 0x40000000) ? ((1 + this.rawSet.size()) + ((this.rawSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            rawSet.addAll(this.rawSet);
            rawSet = java.util.Collections.unmodifiableSet(rawSet);
    }
    java.util.Set<String> stringSet;
    switch(((this.stringSet == null) ? 0 : this.stringSet.size())) {
        case 0:
            stringSet = java.util.Collections.emptySet();
            break;
        case 1:
            stringSet = java.util.Collections.singleton(this.stringSet.get(0));
            break;
        default:
            stringSet = new java.util.LinkedHashSet<String>(((this.stringSet.size() < 0x40000000) ? ((1 + this.stringSet.size()) + ((this.stringSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            stringSet.addAll(this.stringSet);
            stringSet = java.util.Collections.unmodifiableSet(stringSet);
    }
    return new BuilderSingularSets<T>(dangerMice, octopodes, rawSet, stringSet);
}
Example 2
Project: lombok-intellij-plugin-master  File: SingularMap.java View source code
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public SingularMap<A, B> build() {
    java.util.Map<java.lang.Object, java.lang.Object> rawTypes;
    switch(this.rawTypes$key == null ? 0 : this.rawTypes$key.size()) {
        case 0:
            rawTypes = java.util.Collections.emptyMap();
            break;
        case 1:
            rawTypes = java.util.Collections.singletonMap(this.rawTypes$key.get(0), this.rawTypes$value.get(0));
            break;
        default:
            rawTypes = new java.util.LinkedHashMap<java.lang.Object, java.lang.Object>(this.rawTypes$key.size() < 1073741824 ? 1 + this.rawTypes$key.size() + (this.rawTypes$key.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
            for (int $i = 0; $i < this.rawTypes$key.size(); $i++) rawTypes.put(this.rawTypes$key.get($i), this.rawTypes$value.get($i));
            rawTypes = java.util.Collections.unmodifiableMap(rawTypes);
    }
    java.util.Map<Integer, Float> integers;
    switch(this.integers$key == null ? 0 : this.integers$key.size()) {
        case 0:
            integers = java.util.Collections.emptyMap();
            break;
        case 1:
            integers = java.util.Collections.singletonMap(this.integers$key.get(0), this.integers$value.get(0));
            break;
        default:
            integers = new java.util.LinkedHashMap<Integer, Float>(this.integers$key.size() < 1073741824 ? 1 + this.integers$key.size() + (this.integers$key.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
            for (int $i = 0; $i < this.integers$key.size(); $i++) integers.put(this.integers$key.get($i), this.integers$value.get($i));
            integers = java.util.Collections.unmodifiableMap(integers);
    }
    java.util.Map<A, B> generics;
    switch(this.generics$key == null ? 0 : this.generics$key.size()) {
        case 0:
            generics = java.util.Collections.emptyMap();
            break;
        case 1:
            generics = java.util.Collections.singletonMap(this.generics$key.get(0), this.generics$value.get(0));
            break;
        default:
            generics = new java.util.LinkedHashMap<A, B>(this.generics$key.size() < 1073741824 ? 1 + this.generics$key.size() + (this.generics$key.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
            for (int $i = 0; $i < this.generics$key.size(); $i++) generics.put(this.generics$key.get($i), this.generics$value.get($i));
            generics = java.util.Collections.unmodifiableMap(generics);
    }
    java.util.Map<Number, String> extendsGenerics;
    switch(this.extendsGenerics$key == null ? 0 : this.extendsGenerics$key.size()) {
        case 0:
            extendsGenerics = java.util.Collections.emptyMap();
            break;
        case 1:
            extendsGenerics = java.util.Collections.singletonMap(this.extendsGenerics$key.get(0), this.extendsGenerics$value.get(0));
            break;
        default:
            extendsGenerics = new java.util.LinkedHashMap<Number, String>(this.extendsGenerics$key.size() < 1073741824 ? 1 + this.extendsGenerics$key.size() + (this.extendsGenerics$key.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
            for (int $i = 0; $i < this.extendsGenerics$key.size(); $i++) extendsGenerics.put(this.extendsGenerics$key.get($i), this.extendsGenerics$value.get($i));
            extendsGenerics = java.util.Collections.unmodifiableMap(extendsGenerics);
    }
    return new SingularMap<A, B>(rawTypes, integers, generics, extendsGenerics);
}
Example 3
Project: lombok-master  File: BuilderSingularSets.java View source code
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularSets<T> build() {
    java.util.Set<T> dangerMice;
    switch(((this.dangerMice == null) ? 0 : this.dangerMice.size())) {
        case 0:
            dangerMice = java.util.Collections.emptySet();
            break;
        case 1:
            dangerMice = java.util.Collections.singleton(this.dangerMice.get(0));
            break;
        default:
            dangerMice = new java.util.LinkedHashSet<T>(((this.dangerMice.size() < 0x40000000) ? ((1 + this.dangerMice.size()) + ((this.dangerMice.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            dangerMice.addAll(this.dangerMice);
            dangerMice = java.util.Collections.unmodifiableSet(dangerMice);
    }
    java.util.SortedSet<Number> octopodes = new java.util.TreeSet<Number>();
    if ((this.octopodes != null))
        octopodes.addAll(this.octopodes);
    octopodes = java.util.Collections.unmodifiableSortedSet(octopodes);
    java.util.Set<java.lang.Object> rawSet;
    switch(((this.rawSet == null) ? 0 : this.rawSet.size())) {
        case 0:
            rawSet = java.util.Collections.emptySet();
            break;
        case 1:
            rawSet = java.util.Collections.singleton(this.rawSet.get(0));
            break;
        default:
            rawSet = new java.util.LinkedHashSet<java.lang.Object>(((this.rawSet.size() < 0x40000000) ? ((1 + this.rawSet.size()) + ((this.rawSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            rawSet.addAll(this.rawSet);
            rawSet = java.util.Collections.unmodifiableSet(rawSet);
    }
    java.util.Set<String> stringSet;
    switch(((this.stringSet == null) ? 0 : this.stringSet.size())) {
        case 0:
            stringSet = java.util.Collections.emptySet();
            break;
        case 1:
            stringSet = java.util.Collections.singleton(this.stringSet.get(0));
            break;
        default:
            stringSet = new java.util.LinkedHashSet<String>(((this.stringSet.size() < 0x40000000) ? ((1 + this.stringSet.size()) + ((this.stringSet.size() - 3) / 3)) : java.lang.Integer.MAX_VALUE));
            stringSet.addAll(this.stringSet);
            stringSet = java.util.Collections.unmodifiableSet(stringSet);
    }
    return new BuilderSingularSets<T>(dangerMice, octopodes, rawSet, stringSet);
}
Example 4
Project: intellij-generator-plugin-master  File: TypeToTextFactory.java View source code
public static TypeToTextMapping createDefaultVariableInitialization() {
    return new TypeToTextMapping().put("java.util.Collection", "java.util.Collections." + GENERICS_PLACEHOLDER + "emptySet()", true).put("java.util.Set", "java.util.Collections." + GENERICS_PLACEHOLDER + "emptySet()", true).put("java.util.List", "java.util.Collections." + GENERICS_PLACEHOLDER + "emptyList()", true).put("java.util.ArrayList", "new java.util.ArrayList" + GENERICS_PLACEHOLDER + "()", true).put("java.util.SortedSet", "new java.util.TreeSet" + GENERICS_PLACEHOLDER + "()", true).put("java.util.HashSet", "new java.util.HashSet" + GENERICS_PLACEHOLDER + "()", true).put("java.util.LinkedHashSet", "new java.util.LinkedHashSet" + GENERICS_PLACEHOLDER + "()", true).put("java.util.HashMap", "new java.util.HashMap" + GENERICS_PLACEHOLDER + "()", false);
}
Example 5
Project: cloudbreak-master  File: JsonIoConfig.java View source code
@PostConstruct
public void setupJsonReader() {
    JsonReader.assignInstantiator("com.google.common.collect.RegularImmutableMap", new JsonReader.MapFactory());
    JsonReader.assignInstantiator("com.google.common.collect.EmptyImmutableBiMap", new JsonReader.MapFactory());
    JsonReader.assignInstantiator("com.google.common.collect.SingletonImmutableBiMap", new JsonReader.MapFactory());
    JsonReader.assignInstantiator("java.util.Collections$EmptyMap", new JsonReader.MapFactory());
    JsonReader.assignInstantiator("java.util.Collections$SingletonMap", new JsonReader.MapFactory());
    JsonReader.assignInstantiator("com.google.common.collect.SingletonImmutableList", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("com.google.common.collect.RegularImmutableList", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("java.util.Collections$EmptyList", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("java.util.Collections$SingletonList", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("com.google.common.collect.RegularImmutableSet", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("java.util.Collections$EmptySet", new JsonReader.CollectionFactory());
    JsonReader.assignInstantiator("java.util.Collections$SingletonSet", new JsonReader.CollectionFactory());
}
Example 6
Project: xbnjava-master  File: OrderIntListXmpl.java View source code
public static final void main(String[] ignored) {
    int[] aiNums = new int[] { 1, 11, 29, 12, 13, 19, 7, 2, 6, 16, 10, 15, 112, 18, 20, 3, 8, 5, 9, 14 };
    System.out.println("Unsorted: " + Arrays.toString(aiNums));
    ArrayList<Integer> alNums = new ArrayList<Integer>(aiNums.length);
    for (int i : aiNums) {
        alNums.add(i);
    }
    Collections.sort(alNums);
    System.out.println("Sorted: " + Arrays.toString(alNums.toArray()));
    int ixOf12 = Collections.<Integer>binarySearch(alNums, 12);
    System.out.println("Index of number 12: " + ixOf12);
}
Example 7
Project: gluster-ovirt-poc-master  File: GetVmTemplatesFromStorageDomainQuery.java View source code
@Override
protected void executeQueryCommand() {
    List<VmTemplate> returnValue = DbFacade.getInstance().getVmTemplateDAO().getAllForStorageDomain(getParameters().getStorageDomainId());
    for (VmTemplate template : returnValue) {
        VmTemplateHandler.UpdateDisksFromDb(template);
        java.util.Collections.sort(template.getDiskList(), new ImagesComparerByName());
    }
    Collections.sort(returnValue, Collections.reverseOrder(new VmTemplateComparerByDiskSize()));
    getQueryReturnValue().setReturnValue(returnValue);
}
Example 8
Project: java-8-lambdas-exercises-master  File: TestPerformance.java View source code
@Test
public void allMembers() {
    Album album = new Album("foo", Collections.<Track>emptyList(), singletonList(theBeatles));
    Set<Artist> musicians = album.getAllMusicians().collect(toSet());
    Set<Artist> expectedMusicians = new HashSet<>(SampleData.membersOfTheBeatles);
    expectedMusicians.add(theBeatles);
    assertEquals(expectedMusicians, musicians);
}
Example 9
Project: android-oss-master  File: ConfigFactory.java View source code
@NonNull
public static Config config() {
    final Config.LaunchedCountry US = Config.LaunchedCountry.builder().name("US").currencyCode("USD").currencySymbol("$").trailingCode(true).build();
    final Config.LaunchedCountry GB = Config.LaunchedCountry.builder().name("GB").currencyCode("GBP").currencySymbol("£").trailingCode(false).build();
    final Config.LaunchedCountry CA = Config.LaunchedCountry.builder().name("CA").currencyCode("CAD").currencySymbol("$").trailingCode(true).build();
    return Config.builder().countryCode("US").features(Collections.emptyMap()).launchedCountries(Arrays.asList(US, GB, CA)).build();
}
Example 10
Project: count-db-master  File: LongListCombinator.java View source code
@Override
public LongList combine(LongList first, LongList second) {
    LongList result = new LongList();
    result.addAll(first);
    result.addAll(second);
    Collections.sort(result);
    for (int i = 1; i < result.size(); i++) {
        if (result.get(i - 1).equals(result.get(i))) {
            result.remove(i);
            i--;
        }
    }
    return result;
}
Example 11
Project: docbag-master  File: TableTest.java View source code
@Test
public void testCreate() {
    Table table = new Table(NAME, Collections.<Row>emptyList());
    Assert.assertEquals(NAME, table.getName());
    Assert.assertEquals(Collections.emptyList(), table.getTbody());
    Assert.assertEquals(Collections.emptyList(), table.getThead());
    Assert.assertEquals(Collections.emptyList(), table.getTfoot());
}
Example 12
Project: dwoss-master  File: LastCharSorterTest.java View source code
@Test
public void testSorter() {
    List<String> unsorted = Arrays.asList("11118", "11111", "11117", "11113", "11112", "11115", "71116", "11119", "31110", "51114");
    List<String> sorted = Arrays.asList("31110", "11111", "11112", "11113", "51114", "11115", "71116", "11117", "11118", "11119");
    Collections.sort(unsorted, new LastCharSorter());
    assertEquals(sorted, unsorted);
}
Example 13
Project: enunciate-master  File: BasicProviderModule.java View source code
@Override
public List<DependencySpec> getDependencySpecifications() {
    return Collections.<DependencySpec>singletonList(new DependencySpec() {

        @Override
        public boolean accept(EnunciateModule module) {
            return module instanceof ContextModifyingModule;
        }

        @Override
        public boolean isFulfilled() {
            return true;
        }
    });
}
Example 14
Project: FeedThisToThat-master  File: LinkSet.java View source code
public List<String> getTagNames() {
    List<String> tags = new Vector<String>();
    for (LinkEntry entry : this) {
        for (LinkTag linkTag : entry.getTags()) {
            if (!tags.contains(linkTag.getTag())) {
                tags.add(linkTag.getTag());
            }
        }
    }
    Collections.sort(tags);
    return tags;
}
Example 15
Project: FitBuddy-master  File: BasicSetsTest.java View source code
@Test
public void toString_shouldReturnSetsInformation() throws Exception {
    Set set = new BasicSet();
    double weight = 12.5;
    int maxReps = 15;
    set.setMaxReps(maxReps);
    set.setWeight(12.5);
    SetId setId = new SetId("42");
    set.setSetId(setId);
    Sets sets = new BasicSets(Collections.singletonList(set));
    assertThat(sets.toString(), equalTo("BasicSets [sets=" + "[BasicSet [weight=" + weight + ", maxReps=" + maxReps + ", setId=" + setId.toString() + "]]]"));
}
Example 16
Project: hudson_plugins-master  File: CachingSCMTest.java View source code
@Override
protected void setUp() throws Exception {
    super.setUp();
    hgInstallation = "caching";
    Hudson.getInstance().getDescriptorByType(MercurialInstallation.DescriptorImpl.class).setInstallations(new MercurialInstallation("caching", "", "hg", null, false, true, Collections.<ToolProperty<?>>emptyList()));
    MercurialSCM.CACHE_LOCAL_REPOS = true;
}
Example 17
Project: lombok-pg-master  File: CleanupPlain.java View source code
void test() throws Exception {
    InputStream in = new FileInputStream("in");
    try {
        OutputStream out = new FileOutputStream("out");
        try {
            if (in.markSupported()) {
                out.flush();
            }
        } finally {
            if (out instanceof java.io.Closeable) {
                ((java.io.Closeable) out).close();
            }
        }
    } finally {
        if (java.util.Collections.singletonList(in).get(0) != null) {
            in.close();
        }
    }
}
Example 18
Project: Robin-Client-master  File: LocaleUtils.java View source code
public static List<Locale> getSortedAvailableLocales() {
    List<Locale> result = Arrays.asList(Locale.getAvailableLocales());
    Collections.sort(result, new Comparator<Locale>() {

        @Override
        public int compare(Locale lhs, Locale rhs) {
            return lhs.getDisplayName().compareTo(rhs.getDisplayName());
        }
    });
    return result;
}
Example 19
Project: Work_book-master  File: ShuffleTest.java View source code
public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<Integer>();
    for (int i = 1; i <= 49; i++) {
        numbers.add(i);
    }
    Collections.shuffle(numbers);
    List<Integer> winningCombination = numbers.subList(0, 6);
    Collections.sort(winningCombination);
    System.out.println(winningCombination);
}
Example 20
Project: xstream-for-android-master  File: MapTest.java View source code
public void testSynchronizedMap() {
    final String expected;
    if (JVM.is15()) {
        expected = "" + "<java.util.Collections_-SynchronizedMap serialization=\"custom\">\n" + "  <java.util.Collections_-SynchronizedMap>\n" + "    <default>\n" + "      <m/>\n" + "      <mutex class=\"java.util.Collections$SynchronizedMap\" reference=\"../../..\"/>\n" + "    </default>\n" + "  </java.util.Collections_-SynchronizedMap>\n" + "</java.util.Collections_-SynchronizedMap>";
    } else {
        expected = "" + "<java.util.Collections_-SynchronizedMap>\n" + "  <m/>\n" + "  <mutex class=\"java.util.Collections$SynchronizedMap\" reference=\"..\"/>\n" + "</java.util.Collections_-SynchronizedMap>";
    }
    assertBothWays(Collections.synchronizedMap(new HashMap()), expected);
}
Example 21
Project: galaxy-master  File: KryoUtil.java View source code
public static void registerCommonClasses(Kryo kryo) {
    kryo.register(boolean[].class);
    kryo.register(byte[].class);
    kryo.register(short[].class);
    kryo.register(char[].class);
    kryo.register(int[].class);
    kryo.register(float[].class);
    kryo.register(long[].class);
    kryo.register(double[].class);
    kryo.register(String[].class);
    kryo.register(int[][].class);
    kryo.register(java.util.ArrayList.class);
    kryo.register(java.util.LinkedList.class);
    kryo.register(java.util.HashMap.class);
    kryo.register(java.util.LinkedHashMap.class);
    kryo.register(java.util.TreeMap.class);
    kryo.register(java.util.EnumMap.class);
    kryo.register(java.util.HashSet.class);
    kryo.register(java.util.TreeSet.class);
    kryo.register(java.util.EnumSet.class);
    kryo.register(java.util.Arrays.asList("").getClass(), new ArraysAsListSerializer());
    kryo.register(java.util.Collections.newSetFromMap(new java.util.HashMap()).getClass(), new CollectionsSetFromMapSerializer());
    //        kryo.register(java.util.Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer());
    //        kryo.register(java.util.Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer());
    //        kryo.register(java.util.Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer());
    //        kryo.register(java.util.Collections.singletonList("").getClass(), new CollectionsSingletonListSerializer());
    //        kryo.register(java.util.Collections.singleton("").getClass(), new CollectionsSingletonSetSerializer());
    //        kryo.register(java.util.Collections.singletonMap("", "").getClass(), new CollectionsSingletonMapSerializer());
    kryo.register(java.util.GregorianCalendar.class, new GregorianCalendarSerializer());
    kryo.register(java.lang.reflect.InvocationHandler.class, new JdkProxySerializer());
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);
    SynchronizedCollectionsSerializer.registerSerializers(kryo);
    kryo.addDefaultSerializer(Externalizable.class, new ExternalizableKryoSerializer());
    kryo.addDefaultSerializer(java.lang.ref.Reference.class, new ReferenceSerializer());
}
Example 22
Project: quasar-master  File: KryoUtil.java View source code
public static void registerCommonClasses(Kryo kryo) {
    kryo.register(boolean[].class);
    kryo.register(byte[].class);
    kryo.register(short[].class);
    kryo.register(char[].class);
    kryo.register(int[].class);
    kryo.register(float[].class);
    kryo.register(long[].class);
    kryo.register(double[].class);
    kryo.register(String[].class);
    kryo.register(int[][].class);
    kryo.register(java.util.ArrayList.class);
    kryo.register(java.util.LinkedList.class);
    kryo.register(java.util.HashMap.class);
    kryo.register(java.util.LinkedHashMap.class);
    kryo.register(java.util.TreeMap.class);
    kryo.register(java.util.EnumMap.class);
    kryo.register(java.util.HashSet.class);
    kryo.register(java.util.TreeSet.class);
    kryo.register(java.util.EnumSet.class);
    kryo.register(java.util.Arrays.asList("").getClass(), new ArraysAsListSerializer());
    kryo.register(java.util.Collections.newSetFromMap(new java.util.HashMap()).getClass(), new CollectionsSetFromMapSerializer());
    //        kryo.register(java.util.Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer());
    //        kryo.register(java.util.Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer());
    //        kryo.register(java.util.Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer());
    //        kryo.register(java.util.Collections.singletonList("").getClass(), new CollectionsSingletonListSerializer());
    //        kryo.register(java.util.Collections.singleton("").getClass(), new CollectionsSingletonSetSerializer());
    //        kryo.register(java.util.Collections.singletonMap("", "").getClass(), new CollectionsSingletonMapSerializer());
    kryo.register(java.util.GregorianCalendar.class, new GregorianCalendarSerializer());
    kryo.register(java.lang.reflect.InvocationHandler.class, new JdkProxySerializer());
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);
    SynchronizedCollectionsSerializer.registerSerializers(kryo);
    kryo.addDefaultSerializer(Externalizable.class, new ExternalizableKryoSerializer());
    kryo.addDefaultSerializer(java.lang.ref.Reference.class, new ReferenceSerializer());
}
Example 23
Project: android-sdk-sources-for-api-level-23-master  File: Collections2Test.java View source code
/**
     * java.util.Collections#binarySearch(java.util.List,
     *java.lang.Object)
     */
@SuppressWarnings("unchecked")
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // regression for Harmony-1367
    List localList = new LinkedList();
    assertEquals(-1, Collections.binarySearch(localList, new Object()));
    localList.add(new Object());
    try {
        Collections.binarySearch(localList, new Integer(1));
        fail("Should throw ClassCastException");
    } catch (ClassCastException e) {
    }
}
Example 24
Project: ARTPart-master  File: Collections2Test.java View source code
/**
     * java.util.Collections#binarySearch(java.util.List,
     *java.lang.Object)
     */
@SuppressWarnings("unchecked")
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // regression for Harmony-1367
    List localList = new LinkedList();
    assertEquals(-1, Collections.binarySearch(localList, new Object()));
    localList.add(new Object());
    try {
        Collections.binarySearch(localList, new Integer(1));
        fail("Should throw ClassCastException");
    } catch (ClassCastException e) {
    }
}
Example 25
Project: constellio-master  File: SortFieldsPopulator.java View source code
@Override
public Map<String, Object> populateCopyfields(Metadata metadata, Object value) {
    StringSortFieldNormalizer normalizer = metadata.getSortFieldNormalizer();
    Metadata sortField = metadata.getSortField();
    if (normalizer != null) {
        Object normalizedValue;
        if (value == null) {
            normalizedValue = normalizer.normalizeNull();
        } else {
            normalizedValue = normalizer.normalize((String) value);
        }
        if (normalizedValue == null) {
            normalizedValue = "";
        }
        return singletonMap(sortField.getDataStoreCode(), normalizedValue);
    } else {
        return Collections.emptyMap();
    }
}
Example 26
Project: Stage-master  File: SetValueConverter.java View source code
@Override
public Collection<T> convert(String s) {
    if (s != null && s.length() > 0) {
        final LinkedHashSet<T> result = new LinkedHashSet<T>();
        for (String split : s.split(",")) {
            result.add(valueConverter.convert(split.trim()));
        }
        return Collections.unmodifiableSet(result);
    }
    return emptySet();
}
Example 27
Project: stagemonitor-master  File: SetValueConverter.java View source code
@Override
public Collection<T> convert(String s) {
    if (s != null && s.length() > 0) {
        final LinkedHashSet<T> result = new LinkedHashSet<T>();
        for (String split : s.split(",")) {
            result.add(valueConverter.convert(split.trim()));
        }
        return Collections.unmodifiableSet(result);
    }
    return emptySet();
}
Example 28
Project: barge-master  File: EventServlet.java View source code
@Override
public void configure(WebSocketServletFactory factory) {
    factory.setCreator(new WebSocketCreator() {

        @Override
        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
            // remove all compressions extensions that might be requested by the browser...
            resp.setExtensions(Collections.<ExtensionConfig>emptyList());
            return new EventSocket(events);
        }
    });
}
Example 29
Project: Barista-master  File: ViewTreeAnalyzer.java View source code
public static List<View> getAllChildren(View parent) {
    if (!(parent instanceof ViewGroup)) {
        return Collections.singletonList(parent);
    }
    ArrayList<View> result = new ArrayList<>();
    ViewGroup viewGroup = (ViewGroup) parent;
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        result.addAll(getAllChildren(child));
    }
    return result;
}
Example 30
Project: braintree_java-master  File: UnknownPaymentMethodIT.java View source code
@Test
public void findReturnsNoSubscriptionsAssociatedWithUnknownPaymentMethod() {
    NodeWrapper wrapper = mock(NodeWrapper.class);
    UnknownPaymentMethod unknownPaymentMethod = new UnknownPaymentMethod(wrapper);
    PaymentMethodGateway gateway = mock(PaymentMethodGateway.class);
    when(gateway.find("token")).thenReturn(unknownPaymentMethod);
    PaymentMethod foundPaymentMethod = gateway.find("token");
    assertEquals(foundPaymentMethod.getSubscriptions(), Collections.EMPTY_LIST);
}
Example 31
Project: camunda-bpm-platform-osgi-master  File: ProcessEngineConfigurationFromProperties.java View source code
public void configure(Dictionary<String, String> configuration) {
    for (String key : Collections.list(configuration.keys())) {
        ProcessEngineConfigurationProperties configurationProperty = ProcessEngineConfigurationProperties.getPropertyByKey(key);
        if (configurationProperty == null) {
            Logger.getLogger(this.getClass().getName()).info("Couldn't set value " + configuration.get(key) + " for " + key);
        } else {
            configurationProperty.setPropertyOnConfiguration(this, configuration.get(key));
        }
    }
}
Example 32
Project: cgeo-master  File: DistanceComparatorTest.java View source code
public static void testCompareCaches() {
    final List<Geocache> caches = new ArrayList<>();
    for (int i = 0; i < 37; i++) {
        final Geocache cache = new Geocache();
        if (i % 3 == 0) {
            cache.setCoords(new Geopoint(i, i));
        }
        caches.add(cache);
    }
    Collections.sort(caches, new DistanceComparator(Geopoint.ZERO, caches));
}
Example 33
Project: codeine-master  File: StringsCommandPairTest.java View source code
@Test
public void testSortOrder() {
    StringsCommandPair before = new StringsCommandPair(null, null, null, 1);
    StringsCommandPair after = new StringsCommandPair(null, null, null, 2);
    List<StringsCommandPair> list = Lists.newArrayList(before, after);
    Collections.sort(list, new StringsCommandPair.CommandComparator());
    assertEquals(Lists.newArrayList(after, before), list);
}
Example 34
Project: codjo-control-master  File: SqlNameCodec.java View source code
public static List<String> decodeList(String encodedValue) {
    if (encodedValue == null) {
        return Collections.emptyList();
    }
    String contentWithoutBracket = encodedValue.substring(1, encodedValue.length() - 1);
    if (contentWithoutBracket.trim().length() == 0) {
        return Collections.emptyList();
    }
    String[] split = contentWithoutBracket.split(", ");
    return Arrays.asList(split);
}
Example 35
Project: CoreNLP-master  File: ConcatenationIteratorTest.java View source code
public void testIterator() {
    Collection<String> c1 = Collections.singleton("a");
    Collection<String> c2 = Collections.singleton("b");
    Iterator<String> i = new ConcatenationIterator<String>(c1.iterator(), c2.iterator());
    assertEquals("a", i.next());
    assertEquals("b", i.next());
    assertFalse(i.hasNext());
}
Example 36
Project: CorfuDB-master  File: ReplexStreamViewTest.java View source code
@Before
@Override
public void setRuntime() throws Exception {
    r = getDefaultRuntime().connect();
    // First commit a layout that uses Replex
    Layout newLayout = r.layout.get();
    newLayout.getSegment(0L).setReplicationMode(Layout.ReplicationMode.REPLEX);
    newLayout.getSegment(0L).setReplexes(Collections.singletonList(new Layout.LayoutStripe(Collections.singletonList(defaultConfigurationString))));
    newLayout.setEpoch(1);
    r.getLayoutView().committed(1L, newLayout);
    r.invalidateLayout();
}
Example 37
Project: Dream-master  File: MonitorWeightMedian.java View source code
@Override
public Double compute(List<WildcardPattern> monitors) {
    if (monitors.size() == 0) {
        return null;
    }
    Collections.sort(monitors, WildcardPattern.WEIGHT_COMPARATOR);
    if (monitors.size() % 2 == 0) {
        return (monitors.get(monitors.size() / 2 - 1).getWeight() + monitors.get(monitors.size() / 2).getWeight()) / 2;
    }
    return monitors.get(monitors.size() / 2).getWeight();
}
Example 38
Project: dungeon-master  File: AchievementStoreFactoryTest.java View source code
@Test(expected = IllegalStateException.class)
public void testMakeAchievementStoreShouldReturnLockedStore() throws Exception {
    AchievementBuilder achievementBuilder = new AchievementBuilder();
    achievementBuilder.setId("ACHIEVEMENT");
    List<Achievement> emptyList = Collections.emptyList();
    AchievementStore achievementStore = AchievementStoreFactory.makeAchievementStore(emptyList);
    achievementStore.addAchievement(achievementBuilder.createAchievement());
}
Example 39
Project: fastjson-master  File: JSONObjectFluentTest.java View source code
public void test_fluent() throws Exception {
    JSONObject object = //
    new JSONObject().fluentPut("1", //
    1001).fluentPut("2", 1002);
    Assert.assertEquals(2, object.size());
    //
    object.fluentPutAll(Collections.singletonMap("3", 1003)).fluentPutAll(Collections.singletonMap("4", 1004));
    Assert.assertEquals(4, object.size());
    //
    object.fluentRemove("1").fluentRemove("2");
    Assert.assertEquals(2, object.size());
    object.fluentClear().fluentClear();
    Assert.assertEquals(0, object.size());
}
Example 40
Project: featurehouse_fstcomp_examples-master  File: Main.java View source code
public Object driver(String[] args) throws Throwable {
    setVersion("v2002.08.27");
    Collector collector = (Collector) original(args);
    List misDefined = collector.baliRules.misDefined();
    Collections.sort(misDefined);
    for (Iterator p = misDefined.iterator(); p.hasNext(); ) {
        String rule = (String) p.next();
        System.err.println("rule \"" + rule + "\" is referenced but not defined");
    }
    return collector;
}
Example 41
Project: geoserver-old-master  File: CoverageUtilsTest.java View source code
public void testGetOutputTransparentColor() {
    ParameterDescriptor<Color> pdescriptor = ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR;
    ParameterValue<Color> pvalue = pdescriptor.createValue();
    String key = pdescriptor.getName().getCode();
    Map values = Collections.singletonMap(key, "0xFFFFFF");
    Object value = CoverageUtils.getCvParamValue(key, pvalue, values);
    assertTrue(value instanceof Color);
    assertEquals(Color.WHITE, value);
}
Example 42
Project: geoserver_trunk-master  File: CoverageUtilsTest.java View source code
public void testGetOutputTransparentColor() {
    ParameterDescriptor<Color> pdescriptor = ImageMosaicFormat.OUTPUT_TRANSPARENT_COLOR;
    ParameterValue<Color> pvalue = pdescriptor.createValue();
    String key = pdescriptor.getName().getCode();
    Map values = Collections.singletonMap(key, "0xFFFFFF");
    Object value = CoverageUtils.getCvParamValue(key, pvalue, values);
    assertTrue(value instanceof Color);
    assertEquals(Color.WHITE, value);
}
Example 43
Project: gherkin2-master  File: StepTest.java View source code
@Test
public void shouldProvideArgumentsForOutlineTokens() {
    Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have <number> cukes in <whose> belly", 10, null, null);
    assertEquals(7, step.getOutlineArgs().get(0).getOffset().intValue());
    assertEquals("<number>", step.getOutlineArgs().get(0).getVal());
    assertEquals(25, step.getOutlineArgs().get(1).getOffset().intValue());
    assertEquals("<whose>", step.getOutlineArgs().get(1).getVal());
}
Example 44
Project: Glowstone-master  File: BlockCarrot.java View source code
@Override
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
    if (block.getData() >= CropState.RIPE.ordinal()) {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.CARROT_ITEM, random.nextInt(4) + 1)));
    } else {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.CARROT_ITEM, 1)));
    }
}
Example 45
Project: GlowstonePlusPlus-master  File: BlockCarrot.java View source code
@Override
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
    if (block.getData() >= CropState.RIPE.ordinal()) {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.CARROT_ITEM, random.nextInt(4) + 1)));
    } else {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.CARROT_ITEM, 1)));
    }
}
Example 46
Project: hexagonal-sentimental-master  File: Main.java View source code
public static void main(String[] args) {
    // Lexicon Adapter
    Map<String, Sentiment> dictionary = Collections.singletonMap("Kamoulox", Sentiment.HAPPY);
    // Domain Model
    final SentimentAnalysis service = new SentimentAnalysis(dictionary);
    // API Adapters
    final CommandLineAdapter adapter = new CommandLineAdapter(service, System.out);
    // start
    adapter.adapt(args);
}
Example 47
Project: hibernate-tools-master  File: HibernateUtilTest.java View source code
@Test
public void testGetForeignKey() {
    Table table = new Table();
    Assert.assertNull(HibernateUtil.getForeignKey(table, "foo"));
    Assert.assertNull(HibernateUtil.getForeignKey(table, "bar"));
    table.createForeignKey("foo", Collections.emptyList(), null, null);
    Assert.assertNotNull(HibernateUtil.getForeignKey(table, "foo"));
    Assert.assertNull(HibernateUtil.getForeignKey(table, "bar"));
}
Example 48
Project: infinispan-master  File: CollectionExternalizer.java View source code
@Override
public Collection readObject(ObjectInput input) throws IOException, ClassNotFoundException {
    int magicNumber = input.readUnsignedByte();
    switch(magicNumber) {
        case ARRAY_LIST:
            return MarshallUtil.unmarshallCollection(input, ArrayList::new);
        case LINKED_LIST:
            return MarshallUtil.unmarshallCollectionUnbounded(input, LinkedList::new);
        case SINGLETON_LIST:
            return Collections.singletonList(input.readObject());
        case EMPTY_LIST:
            return Collections.emptyList();
        case HASH_SET:
            return MarshallUtil.unmarshallCollection(input,  s -> new HashSet<>());
        case TREE_SET:
            Comparator<Object> comparator = (Comparator<Object>) input.readObject();
            return MarshallUtil.unmarshallCollection(input,  s -> new TreeSet<>(comparator));
        case SINGLETON_SET:
            return Collections.singleton(input.readObject());
        case SYNCHRONIZED_SET:
            return Collections.synchronizedSet(MarshallUtil.unmarshallCollection(input,  s -> new HashSet<>()));
        case ARRAY_DEQUE:
            return MarshallUtil.unmarshallCollection(input, ArrayDeque::new);
        case READ_ONLY_SEGMENT_AWARE_COLLECTION:
            return MarshallUtil.unmarshallCollection(input, ArrayList::new);
        default:
            throw new IllegalStateException("Unknown Set type: " + magicNumber);
    }
}
Example 49
Project: Inside_Android_Testing-master  File: DummyCollaborator.java View source code
public void doSomethingAsynchronously(final DummyCallback callback) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                callback.onSuccess(Collections.EMPTY_LIST);
            } catch (InterruptedException e) {
                callback.onFail(ERROR_CODE);
                e.printStackTrace();
            }
        }
    }).start();
}
Example 50
Project: intellij-community-master  File: ReturnOfCollectionFieldInspection.java View source code
@Override
@Nullable
protected InspectionGadgetsFix buildFix(Object... infos) {
    final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) infos[1];
    final String text = referenceExpression.getText();
    if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, CommonClassNames.JAVA_UTIL_MAP)) {
        if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, "java.util.SortedMap")) {
            return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableSortedMap(" + text + ')', "java.util.SortedMap");
        }
        return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableMap(" + text + ')', CommonClassNames.JAVA_UTIL_MAP);
    } else if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, CommonClassNames.JAVA_UTIL_COLLECTION)) {
        if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, CommonClassNames.JAVA_UTIL_SET)) {
            if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, "java.util.SortedSet")) {
                return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableSortedSet(" + text + ')', "java.util.SortedSet");
            }
            return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableSet(" + text + ')', CommonClassNames.JAVA_UTIL_SET);
        } else if (TypeUtils.expressionHasTypeOrSubtype(referenceExpression, CommonClassNames.JAVA_UTIL_LIST)) {
            return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableList(" + text + ')', CommonClassNames.JAVA_UTIL_LIST);
        }
        return new ReturnOfCollectionFieldFix("java.util.Collections.unmodifiableCollection(" + text + ')', "java.util.Collection");
    }
    return null;
}
Example 51
Project: jabref-master  File: SentenceAnalyzerTest.java View source code
@Test
public void testGetWords() {
    assertEquals(Arrays.asList("a", "b"), new SentenceAnalyzer("a b").getWords());
    assertEquals(Arrays.asList("a", "b"), new SentenceAnalyzer(" a b ").getWords());
    assertEquals(Collections.singletonList("b "), new SentenceAnalyzer("\"b \" ").getWords());
    assertEquals(Collections.singletonList(" a"), new SentenceAnalyzer(" \\ a").getWords());
}
Example 52
Project: Julez-master  File: StringUtils.java View source code
@SuppressWarnings("rawtypes")
public static String join(Collection items, String separator) {
    items = items == null ? Collections.emptySet() : items;
    separator = separator == null ? "" : separator;
    StringBuilder sb = new StringBuilder();
    int count = 1;
    Iterator it = items.iterator();
    while (it.hasNext()) {
        sb.append(it.next());
        if (count < items.size()) {
            sb.append(separator);
        }
        count++;
    }
    return sb.toString();
}
Example 53
Project: lemon-master  File: MockUserAuthConnector.java View source code
public UserAuthDTO findByKey(String key) {
    UserAuthDTO userAuthDto = new UserAuthDTO();
    userAuthDto.setId(key);
    userAuthDto.setUsername(key);
    userAuthDto.setDisplayName(key);
    userAuthDto.setEnabled(true);
    userAuthDto.setPermissions(Collections.singletonList("*"));
    userAuthDto.setRoles(Collections.singletonList("ROLE_USER"));
    return userAuthDto;
}
Example 54
Project: libgdx-cocostudio-master  File: InputNumberSort.java View source code
public static void main(String[] args) {
    Scanner cin = new Scanner(System.in);
    while (cin.hasNext()) {
        int n = cin.nextInt();
        ArrayList<Integer> num = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            num.add(cin.nextInt());
        }
        Collections.sort(num);
        for (int i = 0; i < n; i++) {
            System.out.print(num.get(i) + " ");
        }
        System.out.println();
    }
}
Example 55
Project: lucene-addons-master  File: TestTermStatComparators.java View source code
@Test
public void testDescendingDFComparator() {
    TermDFTF[] tst = new TermDFTF[] { new TermDFTF("cde", 1, 2), new TermDFTF("bcd", 1, 2), new TermDFTF("abc", 1, 2), new TermDFTF("bbc", 2, 2), new TermDFTF("bbd", 2, 2), new TermDFTF("eee", 3, 2) };
    List<TermDFTF> list = Arrays.asList(tst);
    Collections.sort(list);
    //TODO: add actual test!
    for (int i = 0; i < list.size(); i++) {
    //System.out.println(list.get(i).toString());
    }
}
Example 56
Project: lux-master  File: TinyBinarySolrField.java View source code
@Override
public Iterable<?> getValues(XmlIndexer indexer) {
    TinyBinary tinyBinary = makeTinyBinary(indexer);
    byte[] bytes = tinyBinary.getBytes();
    if (bytes.length > tinyBinary.length()) {
        // copy the bytes - SolrJ doesn't have a way to deal with a reference
        // into a byte array (TODO: see about overriding SolrInputField??)
        bytes = new byte[tinyBinary.length()];
        System.arraycopy(tinyBinary.getBytes(), 0, bytes, 0, tinyBinary.length());
    }
    return Collections.singleton(bytes);
}
Example 57
Project: MMI-master  File: RandomVariableOrderingHeuristic.java View source code
// generates a random variable ordering
// useful for benchmark purposes
public String[] runHeuristic(CNFFormula cnf) {
    List<BooleanVariableInterface> variables = new ArrayList<BooleanVariableInterface>();
    variables.addAll(cnf.getVariables());
    java.util.Collections.shuffle(variables);
    String varOrder[] = new String[variables.size()];
    int i = 0;
    for (BooleanVariableInterface var : variables) {
        varOrder[i++] = var.getID();
    }
    return varOrder;
}
Example 58
Project: MMINT-master  File: RandomVariableOrderingHeuristic.java View source code
// generates a random variable ordering
// useful for benchmark purposes
public String[] runHeuristic(CNFFormula cnf) {
    List<BooleanVariableInterface> variables = new ArrayList<BooleanVariableInterface>();
    variables.addAll(cnf.getVariables());
    java.util.Collections.shuffle(variables);
    String varOrder[] = new String[variables.size()];
    int i = 0;
    for (BooleanVariableInterface var : variables) {
        varOrder[i++] = var.getID();
    }
    return varOrder;
}
Example 59
Project: murex-coding-dojo-master  File: ComparablesTest.java View source code
@Test
public void an_empty_list_is_smaller_than_others() {
    final int lefty = compareLists(Arrays.<Integer>asList(1), Collections.<Integer>emptyList());
    assertEquals(OutCome.LEFT, OutCome.from(lefty));
    final int righty = compareLists(Collections.<Integer>emptyList(), Arrays.<Integer>asList(1));
    assertEquals(OutCome.RIGHT, OutCome.from(righty));
}
Example 60
Project: ngrinder-master  File: ControllerPropertiesKeyMapperTest.java View source code
@Test
public void testMapperCreation() {
    PropertiesKeyMapper propertiesKeyMapper = PropertiesKeyMapper.create("controller-properties.map");
    Set<String> allKeys = propertiesKeyMapper.getAllKeys();
    List<String> all = newArrayList();
    all.addAll(allKeys);
    Collections.sort(all);
    for (String each : all) {
        System.out.println("public static final String PROP_" + each.toUpperCase().replace(".", "_") + " = \"" + each + "\";");
    }
}
Example 61
Project: openblocks-master  File: InventoryShuffleFlimFlam.java View source code
@Override
public boolean execute(EntityPlayerMP target) {
    if (target.openContainer != null && !(target.openContainer instanceof ContainerPlayer))
        return false;
    final ItemStack[] mainInventory = target.inventory.mainInventory;
    List<ItemStack> stacks = Arrays.asList(mainInventory);
    Collections.shuffle(stacks);
    target.inventory.mainInventory = stacks.toArray(mainInventory);
    return true;
}
Example 62
Project: packages_apps_OneStep-master  File: ListUtils.java View source code
public static <T> List<T> getDistinctList(List<T> list, Comparator<? super T> comparator) {
    if (list == null || list.size() <= 1) {
        return list;
    }
    Collections.sort(list, comparator);
    for (int i = 1; i < list.size(); ++i) {
        if (comparator.compare(list.get(i - 1), list.get(i)) == 0) {
            list.remove(i);
            i--;
        }
    }
    return list;
}
Example 63
Project: packtpub-xtext-book-examples-master  File: JavaAnonymousClasses.java View source code
public static void main(String[] args) {
    List<String> strings = new ArrayList<String>();
    strings.add("Second");
    strings.add("First");
    strings.add("Third");
    Collections.sort(strings, new Comparator<String>() {

        public int compare(String arg0, String arg1) {
            return arg0.compareToIgnoreCase(arg1);
        }
    });
    String found = null;
    for (String string : strings) {
        if (string.startsWith("F")) {
            found = string;
            break;
        }
    }
    System.out.println(found);
}
Example 64
Project: ProguardPack-master  File: BeanSort.java View source code
public void compare() {
    Collections.sort(list, new Comparator<User>() {

        @Override
        public int compare(User lhs, User rhs) {
            if (lhs.getAge() < rhs.getAge())
                return -1;
            else if (lhs.getAge() == rhs.getAge())
                return 0;
            else
                return 1;
        }
    });
}
Example 65
Project: querydsl-master  File: PropertiesTest.java View source code
@Test
public void hidden2() {
    QStateHistoryOwner historyOwner = QStateHistoryOwner.stateHistoryOwner;
    List<StateHistoryOwner> historyOwners = Collections.singletonList(new StateHistoryOwner());
    assertEquals(1, CollQueryFactory.from(historyOwner, historyOwners).where(historyOwner.stateHistory.isNull()).fetch().size());
}
Example 66
Project: raidenjpa-master  File: MaxUtil.java View source code
public static Object max(List<QueryResultRow> rows, final List<String> path) {
    if (rows.isEmpty()) {
        throw new RuntimeException("The list is empty");
    }
    List<Object> objects = new ArrayList<Object>();
    for (QueryResultRow row : rows) {
        objects.add(row.get(path));
    }
    Collections.sort(objects, new Comparator<Object>() {

        public int compare(Object o1, Object o2) {
            return ComparatorUtil.compare(o1, o2);
        }
    });
    return objects.get(objects.size() - 1);
}
Example 67
Project: routes-master  File: K.java View source code
/**
	 * Create new LinkedHashMap from list of Objects.
	 * 
	 * @param objects
	 * @return
	 */
@SuppressWarnings("unchecked")
public static <Key, Val> Map<Key, Val> map(Object... objects) {
    if (objects.length % 2 != 0) {
        throw new IllegalArgumentException("arguments should be even number");
    }
    LinkedHashMap<Key, Val> map = new LinkedHashMap<>(objects.length / 2);
    for (int i = 0; i < objects.length; i += 2) {
        map.put((Key) objects[i], (Val) objects[i + 1]);
    }
    return Collections.unmodifiableMap(map);
}
Example 68
Project: Stanford-NLP-master  File: ConcatenationIteratorTest.java View source code
public void testIterator() {
    Collection<String> c1 = Collections.singleton("a");
    Collection<String> c2 = Collections.singleton("b");
    Iterator<String> i = new ConcatenationIterator<String>(c1.iterator(), c2.iterator());
    assertEquals("a", i.next());
    assertEquals("b", i.next());
    assertFalse(i.hasNext());
}
Example 69
Project: TestNG-master  File: TestNamesTest.java View source code
@Test
public void checkWithoutChildSuites() {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG tng = create();
    tng.setTestNames(Collections.singletonList("testGroup2"));
    tng.setTestSuites(Collections.singletonList(getPathToResource("testnames/upstream-suite.xml")));
    tng.addListener(tla);
    tng.run();
    Assert.assertEquals(tla.getFailedTests().size(), 0);
    Assert.assertEquals(tla.getPassedTests().size(), 1);
    Assert.assertEquals(tla.getPassedTests().get(0).getMethod().getMethodName(), "sampleOutputTest2");
}
Example 70
Project: testng_samples-master  File: OrderByPriority.java View source code
@Override
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
    Collections.sort(methods, new Comparator<IMethodInstance>() {

        @Override
        public int compare(IMethodInstance o1, IMethodInstance o2) {
            HasPriority i1 = (HasPriority) o1.getInstance();
            HasPriority i2 = (HasPriority) o2.getInstance();
            return Integer.compare(i1.getPriority(), i2.getPriority());
        }
    });
    return methods;
}
Example 71
Project: tfs-plugin-master  File: ActionHelper.java View source code
public static Action[] create(final Collection<Action> actions, final Action... additionalActions) {
    final int totalCount = actions.size() + additionalActions.length;
    final List<Action> allActions = new ArrayList<Action>(totalCount);
    allActions.addAll(actions);
    Collections.addAll(allActions, additionalActions);
    final Action[] result = allActions.toArray(new Action[totalCount]);
    return result;
}
Example 72
Project: thucydides-master  File: Status.java View source code
public static Status statusLevelFor(int points) {
    List<Status> statusesInDescendingOrder = Arrays.asList(Status.values());
    Collections.reverse(statusesInDescendingOrder);
    for (Status status : statusesInDescendingOrder) {
        if (points >= status.getMinimumPoints()) {
            return status;
        }
    }
    return Bronze;
}
Example 73
Project: vexer-master  File: TranslationTest.java View source code
@Test
public void test() {
    boolean testRes = false;
    try {
        testRes = VilleTranslationsFileTester.testLangFiles(TemplateUiConstants.class, new File("target/classes/META-INF/resources/VILLE/language/extensions/template.trl"), Collections.singletonList("en"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertTrue(testRes);
}
Example 74
Project: webdriver-runner-master  File: AbstractWebDriverTestTestConfiguration.java View source code
@Override
public Iterable<WebDriverProvider> getWebDriverProviders() {
    final WebDriverProvider testWebDriverProvider = new WebDriverProvider() {

        @Override
        public WebDriver getNewWebDriver() throws Exception {
            // just as an example
            return new HtmlUnitDriver();
        }

        @Override
        public String getName() {
            return "hello, world";
        }
    };
    return Collections.singleton(testWebDriverProvider);
}
Example 75
Project: webui-framework-master  File: AlphabeticalInterceptor.java View source code
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
    Comparator<IMethodInstance> alphaByMethodName = new Comparator<IMethodInstance>() {

        public int compare(IMethodInstance m1, IMethodInstance m2) {
            String name1 = m1.getMethod().getMethodName();
            String name2 = m2.getMethod().getMethodName();
            return name1.compareTo(name2);
        }
    };
    Collections.sort(methods, alphaByMethodName);
    return methods;
}
Example 76
Project: wurfl-spring-master  File: WurflManagerFactoryBeanTest.java View source code
@Test
public void customRootAndPatches() throws Exception {
    WurflManagerFactoryBean factory = new WurflManagerFactoryBean(new ClassPathResource("test-wurfl.xml", getClass()));
    factory.setPatchLocations(Collections.singletonList(new ClassPathResource("test-wurfl-patch.xml", getClass())));
    factory.afterPropertiesSet();
    factory.getObject();
}
Example 77
Project: xjava-master  File: HandshakeCalculator.java View source code
List<Signal> calculateHandshake(final int number) {
    final List<Signal> result = new ArrayList<>();
    for (final Signal signal : Signal.values()) {
        if (isBitSet(signal.ordinal(), number)) {
            result.add(signal);
        }
    }
    if (isBitSet(REVERSE_SIGNALS_BIT_POSITION, number)) {
        Collections.reverse(result);
    }
    return result;
}
Example 78
Project: XobotOS-master  File: AbstractDeclaration.java View source code
protected List<AbstractMember> createDeclarationList(List<AbstractMember> list) {
    List<AbstractMember> retval = new ArrayList<AbstractMember>();
    for (AbstractMember member : list) {
        if (member instanceof AbstractDefinition)
            retval.add(((AbstractDefinition) member).getDeclaration());
        else
            retval.add(member);
    }
    return Collections.unmodifiableList(retval);
}
Example 79
Project: ha-jdbc-master  File: CollectionsTest.java View source code
private static <T> void verify(SortedSet<T> immutableSet, SortedSet<T> mutableSet, T value1, T value2) {
    try {
        immutableSet.add(value1);
        Assert.fail();
    } catch (UnsupportedOperationException e) {
    }
    try {
        immutableSet.addAll(java.util.Collections.singleton(value1));
        Assert.fail();
    } catch (UnsupportedOperationException e) {
    }
    try {
        immutableSet.clear();
        Assert.assertTrue(mutableSet.isEmpty());
    } catch (UnsupportedOperationException e) {
        Assert.assertFalse(mutableSet.isEmpty());
    }
    Assert.assertEquals(immutableSet.contains(value1), mutableSet.contains(value1));
    Assert.assertEquals(immutableSet.contains(value2), mutableSet.contains(value2));
    Assert.assertEquals(immutableSet.containsAll(java.util.Collections.emptySet()), mutableSet.containsAll(java.util.Collections.emptySet()));
    Assert.assertEquals(immutableSet.containsAll(java.util.Collections.singleton(0)), mutableSet.containsAll(java.util.Collections.singleton(0)));
    Assert.assertEquals(immutableSet.containsAll(java.util.Collections.singleton(1)), mutableSet.containsAll(java.util.Collections.singleton(1)));
    Iterator<T> iterator = immutableSet.iterator();
    if (!mutableSet.isEmpty()) {
        Assert.assertTrue(iterator.hasNext());
        Assert.assertEquals(iterator.next(), mutableSet.iterator().next());
    }
    Assert.assertFalse(iterator.hasNext());
    try {
        iterator.next();
        Assert.fail();
    } catch (NoSuchElementException e) {
    }
    Assert.assertEquals(immutableSet.isEmpty(), mutableSet.isEmpty());
    try {
        immutableSet.remove(value1);
    } catch (UnsupportedOperationException e) {
    }
    try {
        immutableSet.removeAll(java.util.Collections.singleton(value1));
    } catch (UnsupportedOperationException e) {
    }
    try {
        immutableSet.retainAll(java.util.Collections.singleton(value1));
    } catch (UnsupportedOperationException e) {
    }
    Assert.assertEquals(immutableSet.size(), mutableSet.size());
    Assert.assertArrayEquals(immutableSet.toArray(), mutableSet.toArray());
    Assert.assertSame(immutableSet.comparator(), mutableSet.comparator());
    if (!mutableSet.isEmpty()) {
        Assert.assertEquals(immutableSet.first(), mutableSet.first());
        Assert.assertEquals(immutableSet.last(), mutableSet.last());
    } else {
        try {
            immutableSet.first();
            Assert.fail();
        } catch (NoSuchElementException e) {
        }
        try {
            immutableSet.last();
            Assert.fail();
        } catch (NoSuchElementException e) {
        }
    }
    Assert.assertEquals(immutableSet.headSet(value1), mutableSet.headSet(value1));
    Assert.assertEquals(immutableSet.headSet(value2), mutableSet.headSet(value2));
    Assert.assertEquals(immutableSet.subSet(value1, value2), mutableSet.subSet(value1, value2));
    Assert.assertEquals(immutableSet.tailSet(value1), mutableSet.tailSet(value1));
    Assert.assertEquals(immutableSet.tailSet(value2), mutableSet.tailSet(value2));
}
Example 80
Project: cas-master  File: CollectionUtils.java View source code
/**
     * Convert the object given into a {@link Collection} instead.
     *
     * @param obj the object to convert into a collection
     * @return The collection instance containing the object provided
     */
@SuppressWarnings("unchecked")
public static Set<Object> toCollection(final Object obj) {
    final Set<Object> c = new HashSet<>();
    if (obj == null) {
        LOGGER.debug("Converting null obj to empty collection");
    } else if (obj instanceof Collection) {
        c.addAll((Collection<Object>) obj);
        LOGGER.trace("Converting multi-valued attribute [{}]", obj);
    } else if (obj instanceof Map) {
        throw new UnsupportedOperationException(Map.class.getCanonicalName() + " is not supported");
    } else if (obj.getClass().isArray()) {
        Collections.addAll(c, obj);
        LOGGER.trace("Converting array attribute [{}]", obj);
    } else {
        c.add(obj);
        LOGGER.trace("Converting attribute [{}]", obj);
    }
    return c;
}
Example 81
Project: db4o-android-master  File: TypeHandlerConfigurationJDK_1_2.java View source code
public void apply() {
    registerCollection(AbstractCollection.class);
    ignoreFieldsOn(AbstractList.class);
    ignoreFieldsOn(AbstractSequentialList.class);
    ignoreFieldsOn(LinkedList.class);
    ignoreFieldsOn(ArrayList.class);
    ignoreFieldsOn(Vector.class);
    ignoreFieldsOn(Stack.class);
    ignoreFieldsOn(AbstractSet.class);
    ignoreFieldsOn(HashSet.class);
    registerMap(AbstractMap.class);
    registerMap(Hashtable.class);
    ignoreFieldsOn(HashMap.class);
    ignoreFieldsOn(WeakHashMap.class);
    registerTypeHandlerFor(BigSet.class, new BigSetTypeHandler());
    registerTypeHandlerFor(TreeSet.class, new TreeSetTypeHandler() {

        @Override
        protected TreeSet create(Comparator comparator) {
            return new TreeSet(comparator);
        }
    });
    registerTypeHandlerFor(ActivatableTreeSet.class, new TreeSetTypeHandler() {

        @Override
        protected TreeSet create(Comparator comparator) {
            return new ActivatableTreeSet(comparator);
        }
    });
    registerTypeHandlerFor("java.util.Collections$UnmodifiableRandomAccessList", new UnmodifiableListTypeHandler());
    ignoreFieldsOn("java.util.Collections$UnmodifiableList");
    ignoreFieldsOn("java.util.Collections$UnmodifiableCollection");
}
Example 82
Project: operaprestodriver-master  File: DefaultTestEnvironment.java View source code
/**
   * Set an environment variable inside the JVM.
   *
   * http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java/496849#496849
   *
   * @param key   the new environment variable's identifier
   * @param value the new environment variable's value
   */
@SuppressWarnings("unchecked")
public void set(String key, String value) {
    if (value == null) {
        value = "";
    }
    try {
        Class<?>[] classes = Collections.class.getDeclaredClasses();
        Map<String, String> env = System.getenv();
        for (Class<?> cl : classes) {
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                Map<String, String> map = (Map<String, String>) obj;
                map.put(key, value);
            }
        }
    } catch (IllegalAccessException e) {
    } catch (NoSuchFieldException e) {
    }
}
Example 83
Project: strongback-java-master  File: Collections.java View source code
/**
     * Create an immutable set from the supplied items.
     *
     * @param elements the elements to put into the new immutable set
     * @return the new immutable set; never null but possibly empty if {@code elements} is null or empty
     * @param <T> the type of elements in the set
     */
public static <T> Set<T> immutableSet(@SuppressWarnings("unchecked") T... elements) {
    if (elements == null || elements.length == 0)
        return emptySet();
    Set<T> result = new LinkedHashSet<>(elements.length);
    for (T element : elements) {
        if (element != null)
            result.add(element);
    }
    return java.util.Collections.unmodifiableSet(result);
}
Example 84
Project: 99-problems-master  File: P49.java View source code
public static List<String> gray(int n) {
    if (n == 1) {
        return Arrays.asList("0", "1");
    }
    List<String> original = gray(n - 1);
    List<String> reversed = new ArrayList<>(original);
    Collections.reverse(reversed);
    return Stream.concat(original.stream().map( s -> "0" + s), reversed.stream().map( s -> "1" + s)).collect(toList());
}
Example 85
Project: AcademicTorrents-Downloader-master  File: CompleteAnalyzer.java View source code
@Override
public Integer analyze() {
    Comparator<Piece> complete = new Comparator<Piece>() {

        @Override
        public int compare(Piece o1, Piece o2) {
            return (int) (o1.getRequests().get(0).getReceived() - o2.getRequests().get(0).getReceived());
        }
    };
    Piece last = Collections.max(pieces, complete);
    return (int) last.getRequests().get(0).getReceived();
}
Example 86
Project: AdvancedSystemsManager-master  File: Metadata.java View source code
public static ModMetadata init(ModMetadata metadata) {
    metadata.modId = Reference.ID;
    metadata.name = Reference.NAME;
    metadata.description = "Advanced Systems Manager is a forked and updated version of Vswe's Steve's Factory Manager mod";
    metadata.url = "https://github.com/hilburn/AdvancedSystemsManager";
    metadata.version = Reference.VERSION_FULL;
    metadata.authorList = Collections.singletonList("hilburn");
    metadata.credits = "Credit for the original mod goes to Vswe";
    metadata.autogenerated = false;
    return metadata;
}
Example 87
Project: AlgoDS-master  File: MinimumTimeDifference.java View source code
public static int findMinDifference(List<String> timePoints) {
    int min = Integer.MAX_VALUE;
    List<Integer> list = new ArrayList<>(timePoints.size() * 2);
    for (int i = 0; i < timePoints.size(); i++) {
        String[] ss = timePoints.get(i).split(":");
        int time = Integer.parseInt(ss[0]) * 60 + Integer.parseInt(ss[1]);
        list.add(time);
        list.add(time + 24 * 60);
    }
    Collections.sort(list);
    for (int i = 1; i < list.size(); i++) {
        min = Math.min(min, list.get(i) - list.get(i - 1));
    }
    return min;
}
Example 88
Project: android-bankdroid-master  File: TransactionDetails.java View source code
public List<Transaction> getTransactions() {
    if (activityList != null) {
        List<Transaction> transactions = new ArrayList<>();
        for (AccountActivity activity : activityList) {
            transactions.addAll(activity.getTransactionList());
        }
        return transactions;
    }
    return Collections.emptyList();
}
Example 89
Project: android-calculatorpp-master  File: JsclIntegerParser.java View source code
public JsclInteger parse(@Nonnull Parameters p, @Nullable Generic previousSumElement) throws ParseException {
    int pos0 = p.position.intValue();
    final NumeralBase nb = NumeralBaseParser.parser.parse(p, previousSumElement);
    final String number;
    try {
        number = new Digits(nb).parse(p, previousSumElement);
    } catch (ParseException e) {
        p.position.setValue(pos0);
        throw e;
    }
    try {
        return nb.toJsclInteger(number);
    } catch (NumberFormatException e) {
        throw p.exceptionsPool.obtain(p.position.intValue(), p.expression, Messages.msg_8, Collections.singletonList(number));
    }
}
Example 90
Project: AndroidFileBroadcast-master  File: IpAddress.java View source code
public static String getHostIPAddress() {
    try {
        String ipv4;
        List<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
        if (nilist.size() > 0) {
            for (NetworkInterface ni : nilist) {
                List<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                if (ialist.size() > 0) {
                    for (InetAddress address : ialist) {
                        if (!address.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = address.getHostAddress())) {
                            return ipv4;
                        }
                    }
                }
            }
        }
    } catch (SocketException ex) {
        return "IP generation Exception";
    }
    return "Not Connected to Any Network";
}
Example 91
Project: AndroidNetworkBench-master  File: HeaderMap.java View source code
public static Map<String, String> parse(RawHeaders headers, String header) {
    HashMap<String, String> map = new HashMap<String, String>();
    String value = headers.get(header);
    String[] parts = value.split(";");
    for (String part : parts) {
        String[] pair = part.split("=", 2);
        String key = pair[0].trim();
        String v = null;
        if (pair.length > 1)
            v = pair[1];
        if (v != null && v.endsWith("\"") && v.startsWith("\""))
            v = v.substring(1, v.length() - 1);
        map.put(key, v);
    }
    return Collections.unmodifiableMap(map);
}
Example 92
Project: AndroidSDK-RecipeBook-master  File: Recipe013.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add(new Integer(3));
    list.add(new Integer(4));
    list.add(new Integer(5));
    // シャッフル�
    Collections.shuffle(list);
    // ログ出力
    for (Integer i : list) {
        Log.d(TAG, i.toString());
    }
}
Example 93
Project: antlr4ide-master  File: LiveParseTreeRunnerTest.java View source code
@Test
public void jsonTree() {
    assertEquals("( jsonText  ( jsonObject '{'  ( member '\"number\"' ':'  ( jsonValue  ( jsonString '\"space·inside\"' )  )  )  '}' )  )", new ParseTreeCommand(new PrintWriter(System.out)).run("src/test/resources/Json.g4", null, "dir", Collections.<String>emptyList(), "jsonText", "{\"number\": \"space inside\"}"));
}
Example 94
Project: ArchStudio5-master  File: LauncherMyxComponent.java View source code
public List<ILaunchData> getLaunchData() {
    launcher.getLaunchData();
    Object[] res = results.getReturnValues();
    List<ILaunchData> l = new ArrayList<ILaunchData>();
    for (Object re : res) {
        if (re != null) {
            l.add((ILaunchData) re);
        }
    }
    Collections.sort(l, new Comparator<ILaunchData>() {

        @Override
        public int compare(ILaunchData o1, ILaunchData o2) {
            String n1 = o1.getName();
            String n2 = o2.getName();
            return n1.compareTo(n2);
        }
    });
    return Collections.unmodifiableList(l);
}
Example 95
Project: arquillian-cube-master  File: SpdyChannelWithoutFlowControl.java View source code
@Override
synchronized int grabFlowControlBytes(final int bytesToGrab) {
    //Doing by this way the window will always have space so the connection will not hang anymore.
    currentWindowSize += bytesToGrab;
    updateSettings(Collections.singletonList(new SpdySetting(0, SpdySetting.SETTINGS_INITIAL_WINDOW_SIZE, currentWindowSize)));
    super.updateReceiveFlowControlWindow(currentWindowSize);
    // no flow control
    return super.grabFlowControlBytes(bytesToGrab);
}
Example 96
Project: Assignments-master  File: UserInputChecker.java View source code
public ArrayList<String> checkArrayOfStrings(JTextField input) {
    String token = null;
    ArrayList<String> syno = new ArrayList<String>();
    String[] splitActionCommand = null;
    try {
        token = input.getText().trim();
        splitActionCommand = token.split(",");
    } catch (NumberFormatException e) {
        System.out.println("Invalid input:" + input);
    }
    Collections.addAll(syno, splitActionCommand);
    return syno;
}
Example 97
Project: baleen-master  File: AnalysisEngineActionTest.java View source code
@Test
public void test() {
    AnalysisEngineAction aea = new AnalysisEngineAction(ImmutableSet.of(Annotation.class), Collections.emptySet());
    assertEquals(1, aea.getInputs().size());
    assertTrue(aea.getInputs().contains(Annotation.class));
    assertEquals(0, aea.getOutputs().size());
    assertNotNull(aea.toString());
}
Example 98
Project: bean-query-master  File: KeyValueMapSelectorTest.java View source code
@Test
public void testSelectoFromNullList() {
    //given
    KeyValueMapSelector selector = new KeyValueMapSelector() {

        @Override
        protected Map<String, Object> doSelect(Object item) {
            return Collections.emptyMap();
        }
    };
    //when
    List<Map<String, Object>> result = selector.select((List<Object>) null);
    //then
    assertThat(result, empty());
}
Example 99
Project: betsy-master  File: TestsPerGroup.java View source code
public static void main(String... args) {
    System.out.println("Showing only BPEL groups");
    BPELProcessRepository processRepository = BPELProcessRepository.INSTANCE;
    List<String> names = processRepository.getNames();
    List<String> output = new LinkedList<>();
    for (String name : names) {
        int size = processRepository.getByName(name).size();
        if (size < 10) {
            output.add("00" + size + "\t" + name);
        } else if (size < 100) {
            output.add("0" + size + "\t" + name);
        } else {
            output.add(Integer.toString(size) + "\t" + name);
        }
    }
    Collections.sort(output);
    output.forEach(System.out::println);
}
Example 100
Project: brightspot-cms-master  File: MetadataBeforeSave.java View source code
@Override
public void beforeSave(StorageItem storageItem, StorageItemUploadPart part) {
    if (part != null) {
        Map<String, Object> metadata = new LinkedHashMap<>();
        metadata.put("originalFilename", part.getName());
        Map<String, List<String>> httpHeaders = new LinkedHashMap<>();
        httpHeaders.put("Cache-Control", Collections.singletonList("public, max-age=31536000"));
        httpHeaders.put("Content-Length", Collections.singletonList(String.valueOf(part.getSize())));
        httpHeaders.put("Content-Type", Collections.singletonList(part.getContentType()));
        metadata.put("http.headers", httpHeaders);
        storageItem.getMetadata().putAll(metadata);
    }
}
Example 101
Project: cagrid2-master  File: LdapNameComparator.java View source code
@Override
public int compare(LdapName name0, LdapName name1) {
    Set<Attribute> atts0 = Collections.emptySet();
    try {
        atts0 = DNDissector.dissect(name0);
    } catch (NamingException ignored) {
    }
    Set<Attribute> atts1 = Collections.emptySet();
    try {
        atts1 = DNDissector.dissect(name1);
    } catch (NamingException ignored) {
    }
    int rc = atts0.size() - atts1.size();
    if (rc == 0) {
        // If no attributes don't compare as equal.
        if (atts0.size() == 0)
            rc = -1;
        else
            rc = atts0.containsAll(atts1) ? 0 : -1;
    }
    return rc;
}