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: 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 2
Project: ARTPart-master  File: Collections2Test.java View source code
/**
     * java.util.Collections#rotate(java.util.List, int)
     */
public void test_rotateLjava_util_ListI() {
    // Regression for HARMONY-19 Rotate an *empty* list
    Collections.rotate(new ArrayList<Object>(), 25);
    // Regression for HARMONY-20
    List<String> list = new ArrayList<String>();
    list.add(0, "zero");
    list.add(1, "one");
    list.add(2, "two");
    list.add(3, "three");
    list.add(4, "four");
    Collections.rotate(list, Integer.MIN_VALUE);
    assertEquals("Rotated incorrectly at position 0, ", "three", list.get(0));
    assertEquals("Rotated incorrectly at position 1, ", "four", list.get(1));
    assertEquals("Rotated incorrectly at position 2, ", "zero", list.get(2));
    assertEquals("Rotated incorrectly at position 3, ", "one", list.get(3));
    assertEquals("Rotated incorrectly at position 4, ", "two", list.get(4));
}
Example 3
Project: GlowstonePlusPlus-master  File: BlockPotato.java View source code
@Override
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
    if (block.getData() >= CropState.RIPE.ordinal()) {
        if (random.nextInt(100) < 2) {
            return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, random.nextInt(4) + 1), new ItemStack(Material.POISONOUS_POTATO, 1)));
        } else {
            return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, random.nextInt(4) + 1)));
        }
    } else {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, 1)));
    }
}
Example 4
Project: nmonvisualizer-master  File: XMLParserHelper.java View source code
public static Map<String, String> parseAttributes(String unparsedAttributes) {
    if ((unparsedAttributes == null) || "".equals(unparsedAttributes)) {
        return java.util.Collections.emptyMap();
    }
    String[] parts = ATTRIBUTE_SPLIITTER.split(unparsedAttributes);
    int size = parts.length / 2;
    Map<String, String> attributes = new java.util.HashMap<String, String>(size);
    // drop odd numbered end index from array
    size *= 2;
    for (int i = 0; i < size; ) {
        attributes.put(DataHelper.newString(parts[i++].trim()), DataHelper.newString(parts[i++].trim()));
    }
    return attributes;
}
Example 5
Project: sonar-java-master  File: EnumSetCheck.java View source code
public void doSomething(Set<COLOR> param) {
    // compliant, we ignore parameters.
    // Noncompliant [[sc=23;ec=43]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> warm = new HashSet<COLOR>();
    Set foo = new HashSet();
    warm.add(COLORS.RED);
    warm.add(COLORS.ORANGE);
    SetString ss;
    SetColor sc;
    // Compliant, we check only initializer.
    ExtendedSet<COLOR> es;
    // Noncompliant [[sc=17;ec=37]] {{Convert this Set to an EnumSet.}}
    Set warm2 = new HashSet<COLOR>();
    EnumSet<COLOR> warm3 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<COLOR> warm4 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<Integer> ports2 = new HashSet<>();
    // Noncompliant [[sc=24;ec=39]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> ports = new HashSet<>();
    SetColor ports3 = new HashSet<>();
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports4 = Sets.immutableEnumSet(COLOR.RED);
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports5 = Sets.immutableEnumSet(Lists.newArrayList(COLOR.RED));
    Collection<COLOR> col = new ArrayList<>();
    Set<COLOR> col2 = java.util.Collections.unmodifiableSet(EnumSet.of(COLOR.RED, COLOR.ORANGE));
    // Noncompliant
    Set<COLOR> col3 = java.util.Collections.unmodifiableSet(new HashSet<COLOR>());
}
Example 6
Project: OSM2World-master  File: OutlineNodeWorldObject.java View source code
/**
	 * @return  a triangulation of the area covered by this junction
	 */
protected Collection<TriangleXYZ> getTriangulation() {
    if (getOutlinePolygonXZ() == null)
        return emptyList();
    Collection<TriangleXZ> trianglesXZ = TriangulationUtil.triangulate(getOutlinePolygonXZ(), Collections.<SimplePolygonXZ>emptyList());
    Collection<TriangleXYZ> trianglesXYZ = new ArrayList<TriangleXYZ>(trianglesXZ.size());
    for (TriangleXZ triangleXZ : trianglesXZ) {
        VectorXYZ v1 = connectors.getPosXYZ(triangleXZ.v1);
        VectorXYZ v2 = connectors.getPosXYZ(triangleXZ.v2);
        VectorXYZ v3 = connectors.getPosXYZ(triangleXZ.v3);
        if (triangleXZ.isClockwise()) {
            trianglesXYZ.add(new TriangleXYZ(v3, v2, v1));
        } else {
            trianglesXYZ.add(new TriangleXYZ(v1, v2, v3));
        }
    }
    return trianglesXYZ;
}
Example 7
Project: j2objc-master  File: CollectionsTest.java View source code
/**
	 * @tests java.util.Collections#binarySearch(java.util.List,
	 *        java.lang.Object)
	 */
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // Test for method int
    // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
    // assumes ll is sorted and has no duplicate keys
    final int llSize = ll.size();
    // Ensure a NPE is thrown if the list is NULL
    try {
        Collections.binarySearch(null, new Object());
        fail("Expected NullPointerException for null list parameter");
    } catch (NullPointerException e) {
    }
    for (int counter = 0; counter < llSize; counter++) {
        assertEquals("Returned incorrect binary search item position", ll.get(counter), ll.get(Collections.binarySearch(ll, ll.get(counter))));
    }
}
Example 8
Project: org.openntf.domino-master  File: PrintFunctionSet.java View source code
@Override
public void run() {
    Factory.enableCounters(true, false);
    try {
        System.out.println("Currently supported functions");
        List<Function> funcs = new ArrayList<Function>();
        funcs.addAll(Formulas.getFunctionFactory().getFunctions().values());
        Collections.sort(funcs, new Comparator<Function>() {

            @Override
            public int compare(final Function o1, final Function o2) {
                return o1.toString().compareTo(o2.toString());
            }
        });
        for (Function func : funcs) {
            System.out.println(func);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 9
Project: molgenis-master  File: ElasticsearchIndexManagerServiceImpl.java View source code
@Override
@PreAuthorize("hasAnyRole('ROLE_SU, ROLE_PLUGIN_READ_indexmanager')")
public List<EntityType> getIndexedEntities() {
    // collect indexed repos
    List<EntityType> indexedEntityTypeList = new ArrayList<>();
    dataService.getEntityNames().forEach( entityName -> {
        Repository<Entity> repository = dataService.getRepository(entityName);
        if (repository != null && repository.getCapabilities().contains(RepositoryCapability.INDEXABLE)) {
            indexedEntityTypeList.add(repository.getEntityType());
        }
    });
    // sort indexed repos by entity label
    Collections.sort(indexedEntityTypeList, ( e1,  e2) -> e1.getLabel().compareTo(e2.getLabel()));
    return indexedEntityTypeList;
}
Example 10
Project: LambdaDojo-master  File: S206LambdaForCompositeFunction.java View source code
private void sortPerson() {
    List<Person> persons = Arrays.asList(new Person("James", "Brown"), new Person("David", "Crosby"), new Person("James", "Taylor"), new Person("Jackson", "Brown"), new Person("Neil", "Young"), new Person("Coco", "Taylor"));
    Comparator<Person> comparator = new Comparator<Person>() {

        @Override
        public int compare(Person p1, Person p2) {
            // 姓で比較
            String last1 = p1.getLast();
            String last2 = p2.getLast();
            int result = last1.compareTo(last2);
            if (result != 0) {
                return result;
            } else {
                // 姓が同じ場合、名で比較
                String first1 = p1.getFirst();
                String first2 = p2.getFirst();
                return first1.compareTo(first2);
            }
        }
    };
    Collections.sort(persons, comparator);
    System.out.println(persons);
}
Example 11
Project: liferay-ide-master  File: SDKClasspathProvider.java View source code
@Override
public IRuntimeClasspathEntry[] computeUnresolvedClasspath(ILaunchConfiguration configuration) throws CoreException {
    IRuntimeClasspathEntry[] retval = null;
    IRuntimeClasspathEntry[] superEntries = super.computeUnresolvedClasspath(configuration);
    boolean separateVM = AntLaunchingUtil.isSeparateJREAntBuild(configuration);
    if (separateVM) {
        List<IRuntimeClasspathEntry> newEntries = new ArrayList<IRuntimeClasspathEntry>();
        Collections.addAll(newEntries, superEntries);
        AntCorePreferences prefs = AntCorePlugin.getPlugin().getPreferences();
        IAntClasspathEntry[] antClasspathEntries = prefs.getContributedClasspathEntries();
        for (int i = 0; i < antClasspathEntries.length; i++) {
            newEntries.add(JavaRuntime.newStringVariableClasspathEntry(antClasspathEntries[i].getLabel()));
        }
        retval = newEntries.toArray(new IRuntimeClasspathEntry[0]);
    } else {
        retval = superEntries;
    }
    return retval;
}
Example 12
Project: dashboard-master  File: NumberOfUnitTestsImpl.java View source code
@Override
public Integer getValue() {
    class UnitTestComparator implements Comparator<Build> {

        @Override
        public int compare(Build o1, Build o2) {
            Action test1 = getTestReport(o1);
            Action test2 = getTestReport(o2);
            if (test1 == null && test2 == null)
                return 0;
            if (test1 == null)
                return 1;
            if (test2 == null)
                return -1;
            return test1.getTotalCount() - test2.getTotalCount();
        }
    }
    List<Build> builds = service.getBuilds(project);
    if (builds.isEmpty())
        return null;
    Build buildWithMaxUnitTests = Collections.max(builds, new UnitTestComparator());
    Action testReport = getTestReport(buildWithMaxUnitTests);
    return testReport == null ? null : testReport.getTotalCount();
}
Example 13
Project: cloudtm-data-platform-master  File: ConverterClassAwareDmlCompiler.java View source code
public static void main(String[] args) throws Exception {
    final int c = args.length;
    final int offset = c - 3;
    final File dir = new File(args[offset]);
    final String[] baseArgs;
    if (dir.exists() && dir.isDirectory()) {
        final List<String> dmlFilenames = new ArrayList<String>();
        for (final File file : dir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".dml")) {
                dmlFilenames.add(file.getCanonicalPath());
            }
        }
        Collections.sort(dmlFilenames);
        List<URL> pluginDmlUrlList = PluginDmlUrlLoader.getPluginDmlUrlList();
        baseArgs = new String[c - 3 + dmlFilenames.size() + pluginDmlUrlList.size()];
        System.arraycopy(args, 0, baseArgs, 0, offset);
        int i = offset;
        for (URL pluginDmlUrl : pluginDmlUrlList) {
            baseArgs[i++] = pluginDmlUrl.toExternalForm();
        }
        for (final String dmlFilename : dmlFilenames) {
            baseArgs[i++] = dmlFilename;
        }
    } else {
        baseArgs = Arrays.copyOfRange(args, 0, c - 2);
    }
    DmlCompiler.main(baseArgs);
}
Example 14
Project: java8-tutorial-master  File: Lambda1.java View source code
public static void main(String[] args) {
    List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
    Collections.sort(names, new Comparator<String>() {

        @Override
        public int compare(String a, String b) {
            return b.compareTo(a);
        }
    });
    Collections.sort(names, (String a, String b) -> {
        return b.compareTo(a);
    });
    Collections.sort(names, (String a, String b) -> b.compareTo(a));
    Collections.sort(names, ( a,  b) -> b.compareTo(a));
    System.out.println(names);
    names.sort(Collections.reverseOrder());
    System.out.println(names);
    List<String> names2 = Arrays.asList("peter", null, "anna", "mike", "xenia");
    names2.sort(Comparator.nullsLast(String::compareTo));
    System.out.println(names2);
    List<String> names3 = null;
    Optional.ofNullable(names3).ifPresent( list -> list.sort(Comparator.naturalOrder()));
    System.out.println(names3);
}
Example 15
Project: tapestry-model-master  File: DefaultExclusionsBMModifierTest.java View source code
@Test
void exclude() {
    BeanModel model = mockBeanModel();
    DescriptorService descriptorService = newMock(DescriptorService.class);
    TynamoClassDescriptorImpl classDescriptor = new TynamoClassDescriptorImpl(Foo.class);
    IdentifierDescriptor idProp = new IdentifierDescriptorImpl(Foo.class, "id", String.class);
    TynamoPropertyDescriptor multiWordProp = new TynamoPropertyDescriptorImpl(Foo.class, "multiWordProperty", String.class);
    CollectionDescriptor bazzesDescriptor = new CollectionDescriptor(Foo.class, "bazzes", Set.class);
    bazzesDescriptor.setElementType(Baz.class);
    Collections.addAll(classDescriptor.getPropertyDescriptors(), idProp, multiWordProp, bazzesDescriptor);
    expect(model.exclude("id", "bazzes")).andReturn(model);
    expect(model.getBeanType()).andReturn(Foo.class);
    expect(descriptorService.getClassDescriptor(Foo.class)).andReturn(classDescriptor);
    replay();
    DefaultExclusionsBMModifier modifier = new DefaultExclusionsBMModifier(descriptorService);
    modifier.modify(model, PageType.LIST.getContextKey());
    verify();
}
Example 16
Project: raylew_algorithm-master  File: 突击战.java View source code
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int m = scan.nextInt();
    ArrayList<Data> list = new ArrayList<Data>();
    for (int i = 0; i < m; i++) {
        int x = scan.nextInt();
        int y = scan.nextInt();
        Data d = new Data(x, y);
        list.add(d);
    }
    Collections.sort(list);
    int t1 = 0, t2 = 0;
    for (int i = 0; i < list.size(); i++) {
        Data d = list.get(i);
        if (i == 0) {
            t1 = d.x;
            t2 = d.y + t1;
            continue;
        }
        if (t1 + d.x + d.y < t2) {
            t1 += d.x;
        } else {
            t1 += d.x;
            t2 = d.y + t1;
        }
    }
    System.out.println(t2);
}
Example 17
Project: park-alert-master  File: UserRankServlet.java View source code
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String ranks = "";
    int total = 10;
    HashMap<Integer, String> tmp = new HashMap<Integer, String>();
    for (String user : Container.userRank.keySet()) {
        tmp.put(Container.userRank.get(user), user);
    }
    Collection<Integer> value = Container.userRank.values();
    ArrayList<Integer> ranksList = new ArrayList<Integer>(value);
    Collections.sort(ranksList);
    for (Integer rank : ranksList) {
        if (total == 0) {
            break;
        } else {
            total--;
            ranks = ranks + tmp.get(rank) + ";" + rank + ":";
        }
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println(ranks);
}
Example 18
Project: korsakow-editor-master  File: MoveForwardsAction.java View source code
@Override
public void performAction() {
    WidgetCanvasModel model = interfBuilder.getCanvas().getModel();
    final List<WidgetModel> widgets = model.getWidgets();
    List<WidgetModel> selected = new ArrayList<WidgetModel>(model.getSelectedWidgets());
    Collections.sort(selected, new DepthSort(widgets));
    for (int i = selected.size() - 1; i >= 0; --i) {
        WidgetModel widget = selected.get(i);
        int index = model.indexOfWidget(widget);
        if (index + 2 > widgets.size())
            continue;
        if (index + 1 < widgets.size() && selected.contains(widgets.get(index + 1)))
            // preserve relative ordering
            continue;
        model.addWidget(index + 2, widget);
    }
}
Example 19
Project: sitebricks-master  File: FlatTemplateCompiler.java View source code
public Renderable compile(Class<?> page, Template template) {
    try {
        return registry.textWidget(template.getText(), new MvelEvaluatorCompiler(page));
    } catch (ExpressionCompileException e) {
        final List<CompileError> errors = Arrays.asList(CompileError.in(template.getText()).near(e.getError().getError().getLineNumber()).causedBy(e));
        final List<CompileError> warnings = Collections.emptyList();
        metrics.logErrorsAndWarnings(page, errors, warnings);
        throw new TemplateCompileException(page, template.getText(), errors, warnings);
    }
}
Example 20
Project: Desktop-master  File: RibbonTaskContributorFactory.java View source code
public void contribute(RibbonBuildContext context, ARibbonContributor parent) {
    hulls.clear();
    context.processChildren(context.getCurrentPath(), this);
    if (!hulls.isEmpty()) {
        Collections.sort(hulls, comparator);
        AbstractRibbonBand<?>[] bands = new AbstractRibbonBand<?>[hulls.size()];
        int count = 0;
        for (ComparableContributorHull<AbstractRibbonBand<?>> hull : hulls) {
            bands[count++] = hull.getObject();
        }
        RibbonTask task = new RibbonTask(TextUtils.removeTranslateComment(TextUtils.getText("ribbon." + getKey())), bands);
        if (parent != null) {
            parent.addChild(task, new ChildProperties(parseOrderSettings(attributes.getProperty("orderPriority", ""))));
        }
    }
}
Example 21
Project: many-ql-master  File: UIRadio.java View source code
@Override
public List<JRadioButton> applyStyles(List<JRadioButton> toComponent) {
    for (JRadioButton _radio : toComponent) {
        Font font = new Font(radio.getStyle().fontName(), Font.PLAIN, radio.getStyle().fontSize());
        Dimension dimension = new Dimension(radio.getStyle().width(), radio.getStyle().height());
        _radio.setPreferredSize(dimension);
        _radio.setSize(dimension);
        _radio.setForeground(radio.getStyle().color());
        _radio.setFont(font);
        Collections.replaceAll(toComponent, _radio, _radio);
    }
    return toComponent;
}
Example 22
Project: uberpay-wallet-master  File: NetworkUtils.java View source code
public static OkHttpClient getHttpClient(Context context) {
    if (httpClient == null) {
        httpClient = new OkHttpClient();
        httpClient.setConnectionSpecs(Collections.singletonList(ConnectionSpec.MODERN_TLS));
        // TODO HTC 300 Crashed due to Network fail - possibly increase timeout rate to 7000 ms
        httpClient.setConnectTimeout(Constants.HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        // Setup cache
        File cacheDir = new File(context.getCacheDir(), Constants.HTTP_CACHE_DIR);
        Cache cache = new Cache(cacheDir, Constants.HTTP_CACHE_SIZE);
        httpClient.setCache(cache);
    }
    return httpClient;
}
Example 23
Project: TextSecureSMP-master  File: CountryListLoader.java View source code
@Override
public ArrayList<Map<String, String>> loadInBackground() {
    Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
    ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
    for (String region : regions) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
        data.put("country_code", "+" + PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
        results.add(data);
    }
    Collections.sort(results, new RegionComparator());
    return results;
}
Example 24
Project: ecms-develop-master  File: TestCreatePortalArtifactsService.java View source code
public void testAddIgnorePortalPlugin() throws Exception {
    IgnorePortalPlugin ignorePortalPlugin = Mockito.mock(IgnorePortalPlugin.class);
    CreatePortalArtifactsServiceImpl artifactService = (CreatePortalArtifactsServiceImpl) getService(CreatePortalArtifactsService.class);
    String[] ignorePortals = { "acme", "classic", "wai" };
    ArrayList<String> ignorePortalsList = new ArrayList<String>();
    Collections.addAll(ignorePortalsList, ignorePortals);
    Mockito.when(ignorePortalPlugin.getIgnorePortals()).thenReturn(ignorePortalsList);
    artifactService.addIgnorePortalPlugin(ignorePortalPlugin);
}
Example 25
Project: snap-desktop-master  File: CloseProductActionTest.java View source code
@Test
public void testFindFirstSourceProduct_IgnoreIndependent() throws Exception {
    Product toBeClosedProduct = new Product("ToBeClosed", "Type", 100, 100);
    Product dependingProduct = new Product("dependingProduct", "Type", 100, 100);
    Product dependentProduct = createDependentProduct(dependingProduct);
    HashSet<Product> stillOpen = new HashSet<>(Collections.singletonList(dependentProduct));
    stillOpen.add(dependingProduct);
    Product firstSourceProduct = CloseProductAction.findFirstSourceProduct(toBeClosedProduct, stillOpen);
    assertNull(firstSourceProduct);
}
Example 26
Project: sosies-generator-master  File: LogWriterTest.java View source code
@Test
public void testMultiThreadingLog_AllOK() throws InterruptedException, ExecutionException {
    final boolean runTimeErrors = false;
    LogWriter.writeTestStart(Thread.currentThread(), "testMultiThreadingLog");
    final Callable<Boolean> logCall = new Callable<Boolean>() {

        public Boolean call() throws Exception {
            try {
                LogWriter.writeSourcePositionCall("1");
                LogWriter.writeAssert(0, Thread.currentThread(), "the.class", "theMethod", null);
                return false;
            } catch (Exception e) {
                return true;
            }
        }
    };
    final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
    final List<Callable<Boolean>> tasks = Collections.nCopies(THREAD_COUNT, logCall);
    final List<Future<Boolean>> results = service.invokeAll(tasks);
    for (final Future<Boolean> future : results) {
        assertEquals(false, future.get());
    }
    LogWriter.writeTestFinish();
}
Example 27
Project: edx-app-android-master  File: MavenRun.java View source code
public static void main(String[] args) throws IOException {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setPomFile(new File("pom.xml"));
    if (args.length > 0) {
        if (args[0] != null && args[1] != null) {
            Properties projectProperties = new Properties();
            projectProperties.setProperty("deviceOS", args[0]);
            projectProperties.setProperty("appPath", args[1]);
            projectProperties.setProperty("osVersion", args[2]);
            projectProperties.setProperty("deviceName", args[3]);
            projectProperties.setProperty("udid", args[4]);
            request.setProperties(projectProperties);
        }
    }
    request.setGoals(Collections.singletonList("test"));
    Invoker invoker = new DefaultInvoker();
    invoker.setMavenHome(new File(System.getenv("M2_HOME")));
    try {
        invoker.execute(request);
    } catch (MavenInvocationException e) {
        e.printStackTrace();
    }
}
Example 28
Project: pmd-eclipse-plugin-master  File: StringArranger.java View source code
public List<String> trimmedLinesIn(String text) {
    String[] lines = text.split("\n");
    if (lines.length < 1)
        return Collections.emptyList();
    List<String> lineSet = new ArrayList<String>(lines.length);
    int startLine = 0;
    while (startLine < lines.length && StringUtil.isEmpty(lines[startLine])) startLine++;
    int endLine = lines.length - 1;
    while (endLine >= 0 && StringUtil.isEmpty(lines[endLine])) endLine--;
    for (int i = startLine; i <= endLine; i++) {
        lineSet.add(lines[i].trim());
    }
    return lineSet;
}
Example 29
Project: eclipse.jdt.core-master  File: DynamicProjectReferences.java View source code
@Override
public List<IProject> getDependentProjects(IBuildConfiguration buildConfiguration) throws CoreException {
    IProject input = buildConfiguration.getProject();
    IJavaProject javaProject = JavaCore.create(input);
    if (javaProject instanceof JavaProject) {
        JavaProject project = (JavaProject) javaProject;
        String[] required = project.projectPrerequisites(project.getResolvedClasspath());
        IWorkspaceRoot wksRoot = input.getWorkspace().getRoot();
        return Arrays.stream(required).sorted().map( name -> wksRoot.getProject(name)).collect(Collectors.toList());
    }
    return Collections.emptyList();
}
Example 30
Project: quickml-master  File: DTBinaryCatBranchReducer.java View source code
@Override
public Optional<AttributeStats<ClassificationCounter>> getAttributeStats(String attribute) {
    Optional<AttributeStats<ClassificationCounter>> attributeStatsOptional = super.getAttributeStats(attribute);
    if (!attributeStatsOptional.isPresent()) {
        return Optional.absent();
    }
    AttributeStats<ClassificationCounter> attributeStats = attributeStatsOptional.get();
    List<ClassificationCounter> attributesWithClassificationCounters = attributeStats.getStatsOnEachValue();
    Collections.sort(attributesWithClassificationCounters, new Comparator<ClassificationCounter>() {

        @Override
        public int compare(ClassificationCounter cc1, ClassificationCounter cc2) {
            double probOfMinority1 = cc1.getCount(minorityClassification) / cc1.getTotal();
            double probOfMinority2 = cc2.getCount(minorityClassification) / cc2.getTotal();
            return Ordering.natural().reverse().compare(probOfMinority1, probOfMinority2);
        }
    });
    return Optional.of(attributeStats);
}
Example 31
Project: lucene-solr-master  File: TestSimpleTrackingShardHandler.java View source code
public void testSolrXmlOverrideAndCorrectShardHandler() throws Exception {
    RequestTrackingQueue trackingQueue = new RequestTrackingQueue();
    TrackingShardHandlerFactory.setTrackingQueue(jettys, trackingQueue);
    // sanity check that our control jetty has the correct configs as well
    TrackingShardHandlerFactory.setTrackingQueue(Collections.singletonList(controlJetty), trackingQueue);
    QueryResponse ignored = query("q", "*:*", "fl", "id", "sort", "id asc");
    int numShardRequests = 0;
    for (List<ShardRequestAndParams> shard : trackingQueue.getAllRequests().values()) {
        for (ShardRequestAndParams shardReq : shard) {
            numShardRequests++;
        }
    }
    TrackingShardHandlerFactory.setTrackingQueue(jettys, null);
    TrackingShardHandlerFactory.setTrackingQueue(Collections.singletonList(controlJetty), null);
}
Example 32
Project: traffic-balance-master  File: OsmandOdb.java View source code
public net.osmand.binary.OsmandOdb.OsmAndStructure buildPartial() {
    if (result == null) {
        throw new IllegalStateException("build() has already been called on this Builder.");
    }
    if (result.mapIndex_ != java.util.Collections.EMPTY_LIST) {
        result.mapIndex_ = java.util.Collections.unmodifiableList(result.mapIndex_);
    }
    if (result.addressIndex_ != java.util.Collections.EMPTY_LIST) {
        result.addressIndex_ = java.util.Collections.unmodifiableList(result.addressIndex_);
    }
    if (result.transportIndex_ != java.util.Collections.EMPTY_LIST) {
        result.transportIndex_ = java.util.Collections.unmodifiableList(result.transportIndex_);
    }
    net.osmand.binary.OsmandOdb.OsmAndStructure returnMe = result;
    result = null;
    return returnMe;
}
Example 33
Project: android_platform_libcore-master  File: OldCollectionsTest.java View source code
/**
     * java.util.Collections#binarySearch(java.util.List,
     *        java.lang.Object, java.util.Comparator)
     */
public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
    // Regression for HARMONY-94
    LinkedList<Integer> lst = new LinkedList<Integer>();
    lst.add(new Integer(30));
    Collections.sort(lst, null);
    int index = Collections.binarySearch(lst, new Integer(2), null);
    assertEquals(-1, index);
    LinkedList<String> lls = new LinkedList<String>();
    lls.add("1");
    lls.add("2");
    lls.add("3");
    lls.add("4");
    lls.add("");
    LinkedList<String> ll = lls;
    try {
        Collections.binarySearch(ll, new Integer(10), null);
        fail("ClassCastException expected");
    } catch (ClassCastException e) {
    }
}
Example 34
Project: geotoolkit-master  File: FactoryMethodTest.java View source code
/**
     * Tests the creation of an object.
     *
     * @throws FactoryException Should never happen.
     */
@Test
public void testCreate() throws FactoryException {
    final Object[] crsFactory = Collections.singleton(FactoryFinder.getCRSFactory(null)).toArray();
    final FactoryMethod fm = FactoryMethod.find(VerticalCRS.class, crsFactory);
    final Map<String, Object> properties = new HashMap<>();
    assertNull(properties.put("datum", CommonCRS.Vertical.MEAN_SEA_LEVEL.datum()));
    assertNull(properties.put("cs", CommonCRS.Vertical.MEAN_SEA_LEVEL.crs().getCoordinateSystem()));
    assertNull(properties.put("name", "Geoidal height"));
    final Object crs = fm.create(properties);
    assertTrue(crs instanceof VerticalCRS);
    assertEquals(new DefaultVerticalCRS(singletonMap(NAME_KEY, "Geoidal height"), CommonCRS.Vertical.MEAN_SEA_LEVEL.datum(), CommonCRS.Vertical.MEAN_SEA_LEVEL.crs().getCoordinateSystem()), crs);
}
Example 35
Project: GeoGig-master  File: BranchListOp.java View source code
protected ImmutableList<Ref> _call() {
    final Predicate<Ref> filter = new Predicate<Ref>() {

        @Override
        public boolean apply(Ref input) {
            if (locals && input.getName().startsWith(Ref.HEADS_PREFIX)) {
                return true;
            }
            if (remotes && input.getName().startsWith(Ref.REMOTES_PREFIX)) {
                return true;
            }
            return false;
        }
    };
    List<Ref> refs = Lists.newArrayList(command(ForEachRef.class).setFilter(filter).call());
    Collections.sort(refs);
    return ImmutableList.copyOf(refs);
}
Example 36
Project: wpcleaner-master  File: ApiQueryPageRequest.java View source code
/**
   * Load special list of pages.
   * 
   * @param query Type of list.
   * @return Special list of pages.
   */
public List<Page> loadQueryPage(EnumQueryPage query) throws APIException {
    Map<String, String> properties = getProperties(ACTION_QUERY, result.getFormat());
    properties.put(PROPERTY_LIST, PROPERTY_LIST_QUERYPAGE);
    properties.put(PROPERTY_PAGE, query.getCode());
    properties.put(PROPERTY_LIMIT, LIMIT_MAX);
    List<Page> list = new ArrayList<Page>();
    int maxSize = getMaxSize(true, ConfigurationValueInteger.MAX_QUERY_PAGE);
    while (result.executeQueryPage(properties, list) && (list.size() < maxSize)) {
    //
    }
    Collections.sort(list);
    return list;
}
Example 37
Project: mkgmap-master  File: ElementTest.java View source code
@Test
public void testEntryIterator() {
    Element el = new Way(1);
    el.addTag("a", "1");
    el.addTag("b", "2");
    el.addTag("c", "3");
    List<String> keys = new ArrayList<String>();
    List<String> values = new ArrayList<String>();
    for (Map.Entry<String, String> ent : el.getTagEntryIterator()) {
        keys.add(ent.getKey());
        values.add(ent.getValue());
    }
    Collections.sort(keys);
    Collections.sort(values);
    assertArrayEquals("list of keys", new String[] { "a", "b", "c" }, keys.toArray());
    assertArrayEquals("list of values", new String[] { "1", "2", "3" }, values.toArray());
}
Example 38
Project: oobd-master  File: MultiCertStoreSpi.java View source code
public Collection engineGetCertificates(CertSelector certSelector) throws CertStoreException {
    boolean searchAllStores = params.getSearchAllStores();
    Iterator iter = params.getCertStores().iterator();
    List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
    while (iter.hasNext()) {
        CertStore store = (CertStore) iter.next();
        Collection certs = store.getCertificates(certSelector);
        if (searchAllStores) {
            allCerts.addAll(certs);
        } else if (!certs.isEmpty()) {
            return certs;
        }
    }
    return allCerts;
}
Example 39
Project: teiid-designer-master  File: CoreMatcherFactory.java View source code
/**
     * @see org.teiid.designer.core.compare.EObjectMatcherFactory#createEObjectMatchers(org.eclipse.emf.ecore.EReference)
     */
@Override
public List createEObjectMatchers(final EReference reference) {
    // Make sure the reference is in the Core metamodel ...
    final EClass containingClass = reference.getEContainingClass();
    final EPackage metamodel = containingClass.getEPackage();
    if (!CorePackage.eINSTANCE.equals(metamodel)) {
        return Collections.EMPTY_LIST;
    }
    // Create the appropriate matchers ...
    final List results = new LinkedList();
    final int featureId = reference.getFeatureID();
    switch(featureId) {
        case CorePackage.ANNOTATION_CONTAINER__ANNOTATIONS:
            results.add(new CoreAnnotationMatcher());
            break;
        case CorePackage.MODEL_ANNOTATION__MODEL_IMPORTS:
            results.add(new CoreModelImportMatcher());
    }
    return results;
}
Example 40
Project: dataverse-master  File: DatasetVersionTest.java View source code
@Test
public void testComparator() {
    DatasetVersion ds1_0 = new DatasetVersion();
    ds1_0.setId(0l);
    ds1_0.setVersionNumber(1l);
    ds1_0.setMinorVersionNumber(0l);
    ds1_0.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds1_1 = new DatasetVersion();
    ds1_1.setId(1l);
    ds1_1.setVersionNumber(1l);
    ds1_1.setMinorVersionNumber(1l);
    ds1_1.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds2_0 = new DatasetVersion();
    ds2_0.setId(2l);
    ds2_0.setVersionNumber(2l);
    ds2_0.setMinorVersionNumber(0l);
    ds2_0.setVersionState(DatasetVersion.VersionState.RELEASED);
    DatasetVersion ds_draft = new DatasetVersion();
    ds_draft.setId(3l);
    ds_draft.setVersionState(DatasetVersion.VersionState.DRAFT);
    List<DatasetVersion> expected = Arrays.asList(ds1_0, ds1_1, ds2_0, ds_draft);
    List<DatasetVersion> actual = Arrays.asList(ds2_0, ds1_0, ds_draft, ds1_1);
    Collections.sort(actual, DatasetVersion.compareByVersion);
    assertEquals(expected, actual);
}
Example 41
Project: dtangler-master  File: SwingDsmFeatureTest.java View source code
@Test
public void testSimpleDsmContent() {
    DependencyGraphBuilder builder = new DependencyGraphBuilder();
    builder.add("foo").dependsOn("bar", 2).and("bay", 3);
    builder.add("bar").dependsOn("bay");
    SwingDsm.getModel().setDsm(new DsmEngine(builder.getDependencies()).createDsm(), new AnalysisResult(Collections.EMPTY_MAP, Collections.EMPTY_SET, true));
    DsmViewDriver dsmView = new DsmViewDriver(SwingDsm.getView().getJComponent());
    assertEquals(4, dsmView.getColumCount());
    assertEquals(3, dsmView.getRowCount());
    assertEquals("  1 foo (0)", dsmView.getCellText(0, 0));
    assertEquals("  2 bar (0)", dsmView.getCellText(1, 0));
    assertEquals("  3 bay (0)", dsmView.getCellText(2, 0));
    assertEquals("", dsmView.getCellText(0, 1));
    assertEquals("2", dsmView.getCellText(1, 1));
    assertEquals("3", dsmView.getCellText(2, 1));
    assertEquals("", dsmView.getCellText(0, 2));
    assertEquals("", dsmView.getCellText(1, 2));
    assertEquals("1", dsmView.getCellText(2, 2));
    assertEquals("", dsmView.getCellText(0, 3));
    assertEquals("", dsmView.getCellText(1, 3));
    assertEquals("", dsmView.getCellText(2, 3));
}
Example 42
Project: smack-xmpp-master  File: TransportCandidateTest.java View source code
/**
     * Test for compareTo()
     */
public void testCompareTo() {
    int highestPref = 100;
    ICECandidate cand1 = new ICECandidate("192.168.2.1", 3, 2, "password", 3468, "username", 1, ICECandidate.Type.prflx);
    ICECandidate cand2 = new ICECandidate("192.168.5.1", 2, 10, "password", 3469, "username", 15, ICECandidate.Type.prflx);
    ICECandidate candH = new ICECandidate("192.168.2.1", 1, 2, "password", 3468, "username", highestPref, ICECandidate.Type.prflx);
    ICECandidate cand3 = new ICECandidate("192.168.2.10", 2, 10, "password", 3469, "username", 2, ICECandidate.Type.prflx);
    ICECandidate cand4 = new ICECandidate("192.168.4.1", 3, 2, "password", 3468, "username", 78, ICECandidate.Type.prflx);
    ArrayList<ICECandidate> candList = new ArrayList<ICECandidate>();
    candList.add(cand1);
    candList.add(cand2);
    candList.add(candH);
    candList.add(cand3);
    candList.add(cand4);
    Collections.sort(candList);
    assertEquals(candList.get(candList.size() - 1), candH);
}
Example 43
Project: streamex-master  File: OrderedCancellableSpliteratorTest.java View source code
@Test
public void testSpliterator() {
    int limit = 10;
    Supplier<List<Integer>> s = ArrayList::new;
    BiConsumer<List<Integer>, Integer> a = ( acc,  t) -> {
        if (acc.size() < limit)
            acc.add(t);
    };
    BinaryOperator<List<Integer>> c = ( a1,  a2) -> {
        a2.forEach( t -> a.accept(a1, t));
        return a1;
    };
    Predicate<List<Integer>> p =  acc -> acc.size() >= limit;
    List<Integer> input = IntStreamEx.range(30).boxed().toList();
    List<Integer> expected = IntStreamEx.range(limit).boxed().toList();
    checkSpliterator("head-short-circuit", Collections.singletonList(expected), () -> new OrderedCancellableSpliterator<>(input.spliterator(), s, a, c, p));
}
Example 44
Project: wisdom-master  File: ResultExample.java View source code
public void example() {
    List<String> errors = Collections.emptyList();
    // tag::results[]
    Result ok = ok("Hello wisdom!");
    Result page = ok(render(template));
    Result notFound = notFound();
    Result pageNotFound = notFound("<h1>Page not found</h1>").as(MimeTypes.HTML);
    Result badRequest = badRequest(render(template, "error", errors));
    Result oops = internalServerError("Oops");
    Result exception = internalServerError(new NullPointerException("Cannot be null"));
    Result anyStatus = status(488).render("Strange response").as(MimeTypes.TEXT);
// end::results[]
}
Example 45
Project: cdo-master  File: DawnWrapperResourceTest.java View source code
public void testPostEventTransactionHandler() throws Exception {
    // TransactionalEditingDomain editingDomain = DawnGMFEditingDomainFactory.getInstance().createEditingDomain();
    CDOSession session = openSession();
    ResourceSet resourceSet = createResourceSet();
    session.openTransaction(resourceSet);
    resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("acore_diagram", new XMIResourceImpl());
    Resource resource = resourceSet.createResource(URI.createURI("dawn://repo1/default10.acore_diagram"));
    assertInstanceOf(CDOResource.class, resource);
    resource.save(Collections.EMPTY_MAP);
    session.close();
}
Example 46
Project: geoserver-enterprise-master  File: WPSAdminPageTest.java View source code
@Test
public void testWorkspace() throws Exception {
    GeoServer geoServer = getGeoServerApplication().getGeoServer();
    WPSInfo wps = geoServer.getService(WPSInfo.class);
    WorkspaceInfo defaultWs = getCatalog().getDefaultWorkspace();
    WPSInfo wps2 = geoServer.getFactory().create(WPSInfo.class);
    OwsUtils.copy(wps, wps2, WPSInfo.class);
    ((ServiceInfoImpl) wps2).setId(null);
    wps2.setWorkspace(defaultWs);
    wps2.setMaintainer("TestMaintainer");
    geoServer.add(wps2);
    // start the page with the custom workspace
    login();
    tester.startPage(WPSAdminPage.class, new PageParameters(Collections.singletonMap("workspace", defaultWs.getName())));
    // print(tester.getLastRenderedPage(), true, true, true);
    // test that components have been filled as expected
    tester.assertModelValue("form:maintainer", "TestMaintainer");
}
Example 47
Project: btpka3.github.com-master  File: TestCasRESTfulApi.java View source code
@SuppressWarnings("unchecked")
public static void test() {
    String casUrlPrefix = "http://login-test.his.com/tcgroup-sso-web";
    String username = "15372712873";
    String password = "123456";
    // GET TGT
    RestTemplate rest = new RestTemplate();
    rest.setMessageConverters(Arrays.asList(new StringHttpMessageConverter(), new FormHttpMessageConverter()));
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("username", username);
    params.set("password", password);
    URI tgtUrl = rest.postForLocation(casUrlPrefix + "/v1/tickets", params, Collections.emptyMap());
    System.out.println("[" + tgtUrl + "]");
    // GET ST
    String service = "http://login-test.his.com/tcgroup-his-web/client/nop.do";
    params.clear();
    params.set("service", service);
    ResponseEntity<String> st = rest.postForEntity(tgtUrl, params, String.class);
    System.out.println("[" + st.getBody() + "]");
    // Using ST get data from SSO app(tcgroup-his-web).
    Map<String, Object> urlParams = new HashMap<String, Object>();
    urlParams.put("ticket", st.getBody());
    ResponseEntity<String> html = rest.getForEntity(service + "?ticket=" + st.getBody(), String.class, urlParams);
    System.out.println("[" + html.getBody() + "]");
}
Example 48
Project: aceim-master  File: ApiObject.java View source code
public static <T extends ApiObject> List<T> parseArray(String json, Class<T> cls) {
    try {
        JSONArray array = new JSONObject(json).getJSONArray("response");
        List<T> list = new ArrayList<T>(array.length());
        for (int i = 0; i < array.length(); i++) {
            JSONObject jo = array.optJSONObject(i);
            T object = null;
            try {
                if (jo != null) {
                    object = cls.getConstructor(JSONObject.class).newInstance(jo);
                } else {
                    Object o = array.get(i);
                    object = cls.getConstructor(o.getClass()).newInstance(o);
                }
            } catch (Exception e) {
                Logger.log(e);
            }
            if (object != null) {
                list.add(object);
            }
        }
        return list;
    } catch (Exception e) {
        Logger.log(e);
    }
    return Collections.emptyList();
}
Example 49
Project: Subsonic-master  File: SearchResultParser.java View source code
public SearchResult parse(Reader reader, ProgressListener progressListener) throws Exception {
    init(reader);
    List<MusicDirectory.Entry> songs = new ArrayList<MusicDirectory.Entry>();
    int eventType;
    do {
        eventType = nextParseEvent();
        if (eventType == XmlPullParser.START_TAG) {
            String name = getElementName();
            if ("match".equals(name)) {
                songs.add(parseEntry(""));
            } else if ("error".equals(name)) {
                handleError();
            }
        }
    } while (eventType != XmlPullParser.END_DOCUMENT);
    validate();
    return new SearchResult(Collections.<Artist>emptyList(), Collections.<MusicDirectory.Entry>emptyList(), songs);
}
Example 50
Project: keycloak-master  File: AbstractIdentityProviderModelTest.java View source code
@Before
public void onBefore() {
    this.expectedProviders = new HashSet<String>();
    this.expectedProviders.add(SAMLIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(OIDCIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(GoogleIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(FacebookIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(GitHubIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(TwitterIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(LinkedInIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders.add(StackoverflowIdentityProviderFactory.PROVIDER_ID);
    this.expectedProviders = Collections.unmodifiableSet(this.expectedProviders);
}
Example 51
Project: revapi-master  File: MovedInHierarchy.java View source code
@Nullable
@Override
protected List<Difference> doEnd() {
    ActiveElements<JavaModelElement> els = popIfActive();
    if (els == null) {
        return null;
    }
    String oldType = Util.toHumanReadableString(els.oldElement.getDeclaringElement().getEnclosingElement().asType());
    String newType = Util.toHumanReadableString(els.newElement.getDeclaringElement().getEnclosingElement().asType());
    //we know that oldEl.isInherited() != newEl.isInherited(), so it's enough to just check for the old
    Code code = els.oldElement.isInherited() ? moveDown : moveUp;
    return Collections.singletonList(createDifference(code, Code.attachmentsFor(els.oldElement, els.newElement, "oldClass", oldType, "newClass", newType)));
}