javatips.net counter

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: TabCompleteHandler.java View source code
@Override
public void handle(GlowSession session, TabCompleteMessage message) {
    final Player sender = session.getPlayer();
    final String buffer = message.getText();
    final List<String> completions = new ArrayList<>();
    // complete command or username
    if (buffer.startsWith("/")) {
        List<String> items = session.getServer().getCommandMap().tabComplete(sender, buffer.substring(1));
        if (items != null) {
            completions.addAll(items);
        }
    } else {
        int space = buffer.lastIndexOf(' ');
        String lastWord;
        if (space == -1) {
            lastWord = buffer;
        } else {
            lastWord = buffer.substring(space + 1);
        }
        // from Command
        for (Player player : session.getServer().getOnlinePlayers()) {
            String name = player.getName();
            if (sender.canSee(player) && StringUtil.startsWithIgnoreCase(name, lastWord)) {
                completions.add(name);
            }
        }
        Collections.sort(completions, String.CASE_INSENSITIVE_ORDER);
    }
    // call event and send response
    EventFactory.callEvent(new PlayerChatTabCompleteEvent(sender, buffer, completions));
    session.send(new TabCompleteResponseMessage(completions));
}
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: GenericSelectionModel.java View source code
public List<OptionModel> getOptions() {
    List<OptionModel> optionModelList = new ArrayList<OptionModel>();
    for (T obj : list) {
        if (labelField == null) {
            optionModelList.add(new OptionModelImpl(obj.toString(), obj));
        } else {
            optionModelList.add(new OptionModelImpl(adapter.get(obj, labelField).toString(), obj));
        }
    }
    if (sortByLabel) {
        Collections.sort(optionModelList, new Comparator<OptionModel>() {

            public int compare(OptionModel o1, OptionModel o2) {
                return o1.getLabel().compareTo(o2.getLabel());
            }
        });
    }
    return optionModelList;
}
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: LinkPool.java View source code
@Override
protected void updateEntry(KCollapsiblePane pane, AbstractHeader header, Content<SnuContentEntry> content, SnuHeaderEntry headerEntry) {
    // TODO: do this in the model
    List<SnuContentEntry> entries = new ArrayList<SnuContentEntry>();
    Collection<ISnu> links;
    try {
        Request request = new Request();
        request.set("id", headerEntry.getSnuId());
        Response response = CommandExecutor.executeCommand(SimulatedSearchCommand.class, request);
        links = (Collection<ISnu>) response.get("results");
    } catch (CommandException e) {
        Application.getInstance().showUnhandledErrorDialog(e);
        links = Collections.EMPTY_LIST;
    }
    for (ISnu link : links) {
        SnuContentEntry contentEntry = new SnuContentEntry(link.getId(), link.getName());
        entries.add(contentEntry);
    }
    Collections.sort(entries);
    content.setModel(entries);
}
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: DisjointSetTest.java View source code
/**
      * Tests the set.
      */
@Test
public void testDisjointSet() {
    DisjointSet<String> t1 = new DisjointSet<>(true);
    DisjointSet<String> t2 = new DisjointSet<>(t1);
    DisjointSet<String> t3 = new DisjointSet<>(t2);
    assertNotNull(t1.getTrash());
    assertSame(t1.getTrash(), t2.getTrash());
    assertSame(t2.getTrash(), t3.getTrash());
    assertTrue(t1.add("alpha"));
    assertTrue(t2.add("bêta"));
    assertTrue(t3.add("gamma"));
    assertTrue(t2.add("delta"));
    assertTrue(t1.add("epsilon"));
    assertTrue(t2.add("alpha"));
    assertTrue(t2.remove("bêta"));
    assertEquals(Collections.singleton("epsilon"), t1);
    assertEquals(new HashSet<>(Arrays.asList(new String[] { "alpha", "delta" })), t2);
    assertEquals(Collections.singleton("gamma"), t3);
    assertEquals(Collections.singleton("bêta"), t1.getTrash());
    assertNotSame(t1, assertSerializedEquals(t1));
    assertNotSame(t2, assertSerializedEquals(t2));
    assertNotSame(t3, assertSerializedEquals(t3));
}
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)));
}
Example 52
Project: android-platform-tools-base-master  File: TestRunResultTest.java View source code
public void testGetNumTestsInState() {
    TestIdentifier test = new TestIdentifier("FooTest", "testBar");
    TestRunResult result = new TestRunResult();
    assertEquals(0, result.getNumTestsInState(TestStatus.PASSED));
    result.testStarted(test);
    assertEquals(0, result.getNumTestsInState(TestStatus.PASSED));
    assertEquals(1, result.getNumTestsInState(TestStatus.INCOMPLETE));
    result.testEnded(test, Collections.EMPTY_MAP);
    assertEquals(1, result.getNumTestsInState(TestStatus.PASSED));
    assertEquals(0, result.getNumTestsInState(TestStatus.INCOMPLETE));
}
Example 53
Project: dashbuilder-master  File: CollectionsDataSetSort.java View source code
public List<Integer> sort(DataSet dataSet, List<Integer> rowNumbers, List<ColumnSort> columnSortList) {
    // Create the comparator.
    DataSetRowComparator comparator = new DataSetRowComparator();
    for (ColumnSort columnSort : columnSortList) {
        DataColumn column = dataSet.getColumnById(columnSort.getColumnId());
        if (column == null)
            throw new IllegalArgumentException("Sort column not found: " + columnSort.getColumnId());
        comparator.criteria(column, columnSort.getOrder());
    }
    // Create the row number list to sort.
    List<Integer> rows = new ArrayList<Integer>();
    if (rowNumbers != null) {
        rows.addAll(rowNumbers);
    } else {
        for (int i = 0; i < dataSet.getRowCount(); i++) {
            rows.add(i);
        }
    }
    // Sort the row numbers.
    Collections.sort(rows, comparator);
    return rows;
}
Example 54
Project: org.eclipse.ecr-master  File: TestDocumentModel.java View source code
@SuppressWarnings({ "ObjectEqualsNull", "SimplifiableJUnitAssertion" })
public void testDocumentModelImpl() throws Exception {
    DocumentModel model = new DocumentModelImpl("my type");
    assertEquals("my type", model.getType());
    // assertNull(model.getACP());
    // assertNull(model.getAdapter(Object.class));
    assertNull(model.getDataModel("toto"));
    assertTrue(model.getDataModels().isEmpty());
    assertTrue(model.getDataModelsCollection().isEmpty());
    assertEquals(Collections.emptySet(), model.getDeclaredFacets());
    assertEquals(0, model.getDeclaredSchemas().length);
    assertEquals(Collections.emptySet(), model.getFacets());
    assertEquals(0, model.getSchemas().length);
    assertNull(model.getId());
    // old
    assertNull(model.getLock());
    assertNull(model.getLockInfo());
    assertNull(model.getName());
    assertNull(model.getParentRef());
    assertNull(model.getPath());
    assertNull(model.getPathAsString());
    assertNull(model.getProperties(""));
    assertNull(model.getProperty("", ""));
    assertNull(model.getRef());
    assertNull(model.getSessionId());
    assertFalse(model.hasFacet(""));
    assertFalse(model.hasSchema(""));
    assertFalse(model.isDownloadable());
    assertFalse(model.isFolder());
    assertFalse(model.isLocked());
    assertFalse(model.isVersionable());
    assertFalse(model.isVersion());
    assertNull(model.getRepositoryName());
    assertNull(model.getSessionId());
    //assertNull(model.getLifeCyclePolicy());
    assertTrue(model.equals(model));
    assertFalse(model.equals(null));
    assertNotNull(model.toString());
}
Example 55
Project: geotools-old-master  File: ShapefileAttributeReaderTest.java View source code
public void testAttributeReader() throws IOException {
    File shpFile = copyShapefiles(STATEPOP);
    URL url = shpFile.toURI().toURL();
    ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
    //creates both indexed and regular shapefile data store
    IndexedShapefileDataStore indexedstore = new IndexedShapefileDataStore(url);
    ShapefileDataStore store = new ShapefileDataStore(url);
    //get a random feature id from one of the stores
    SimpleFeatureIterator it = indexedstore.getFeatureSource().getFeatures().features();
    FeatureId fid = it.next().getIdentifier();
    it.close();
    //query the datastore
    FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
    Filter idFilter = ff.id(Collections.singleton(fid));
    final Query query = new DefaultQuery(indexedstore.getSchema().getName().getLocalPart(), idFilter, new String[] { "STATE_NAME" });
    final SimpleFeatureCollection indexedfeatures = indexedstore.getFeatureSource().getFeatures(query);
    final SimpleFeatureCollection features = store.getFeatureSource().getFeatures(query);
    // compare the results
    SimpleFeatureIterator indexIterator = indexedfeatures.features();
    SimpleFeature indexedFeature = indexIterator.next();
    indexIterator.close();
    SimpleFeatureIterator iterator = features.features();
    SimpleFeature feature = iterator.next();
    iterator.close();
    String indexedStateName = (String) indexedFeature.getAttribute("STATE_NAME");
    String stateName = (String) feature.getAttribute("STATE_NAME");
    // System.out.println(indexedStateName);
    // System.out.println(stateName);
    assertEquals(indexedStateName, stateName);
    store.dispose();
    indexedstore.dispose();
}
Example 56
Project: sqlpower-library-master  File: JTreeCollapseAllAction.java View source code
public void actionPerformed(ActionEvent e) {
    TreePath selected = tree.getSelectionPath();
    Enumeration<TreePath> descendants = tree.getExpandedDescendants(selected);
    if (descendants == null)
        return;
    List<TreePath> paths = Collections.list(descendants);
    // Sort required to make sure the parent is collapsed after child.
    Collections.sort(paths, new Comparator<TreePath>() {

        public int compare(TreePath o1, TreePath o2) {
            return o2.getPathCount() - o1.getPathCount();
        }
    });
    for (TreePath path : paths) {
        tree.collapsePath(path);
    }
    tree.collapsePath(selected);
}
Example 57
Project: extFM-Tooling-master  File: FeatureModelTest.java View source code
private EObject loadTestModel(String filename, String suffix, Factory resourceFactory, ResourceSet resourceSet) {
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(suffix, resourceFactory);
    URL fileresource = this.getClass().getClassLoader().getResource(filename);
    String path = fileresource.getPath();
    URI uri = URI.createFileURI(path);
    Resource resource = resourceSet.getResource(uri, true);
    try {
        resource.load(Collections.EMPTY_MAP);
        System.out.println("Loaded " + uri);
        EList<EObject> contents = resource.getContents();
        if (contents != null && !contents.isEmpty()) {
            return contents.get(0);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 58
Project: dcache-master  File: StandardPoolQueuesService.java View source code
@Override
public List<PoolQueueBean> getPoolQueues() throws PoolQueuesServiceException {
    try {
        Set<Pool> pools = getPoolsDAO().getPools();
        _log.debug("returned pools: " + pools.size());
        List<PoolQueueBean> poolQueues = new ArrayList<>(pools.size());
        Map<String, List<String>> domainMap = getDomainsDAO().getDomainsMap();
        for (Pool currentPool : pools) {
            PoolQueueBean newPoolQueueBean = createPoolQueueBean(currentPool, domainMap);
            poolQueues.add(newPoolQueueBean);
        }
        _log.debug("returned PoolQueueBeans: " + poolQueues.size());
        Collections.sort(poolQueues);
        return poolQueues;
    } catch (DAOException e) {
        throw new PoolQueuesServiceException(e);
    }
}
Example 59
Project: trie4j-master  File: TrieMap.java View source code
@Override
public Set<Map.Entry<String, T>> entrySet() {
    Set<Map.Entry<String, T>> ret = new TreeSet<Map.Entry<String, T>>();
    for (final String s : trie.predictiveSearch("")) {
        final T v = trie.get(s);
        ret.add(new Map.Entry<String, T>() {

            @Override
            public String getKey() {
                return s;
            }

            @Override
            public T getValue() {
                return v;
            }

            @Override
            public T setValue(T value) {
                throw new UnsupportedOperationException();
            }
        });
    }
    return Collections.unmodifiableSet(ret);
}
Example 60
Project: rsimulator-master  File: FileUtilsImpl.java View source code
public List<Path> findRequests(Path path, String extension) {
    List<Path> requests;
    try (Stream<Path> stream = Files.walk(path)) {
        Predicate<Path> predicate =  p -> Files.isRegularFile(p) && p.toFile().getName().endsWith(SUFFIX_PREFIX.concat(extension));
        requests = stream.filter(predicate).collect(Collectors.toList());
        // Do not want depth first as given by Files.walk
        Collections.sort(requests, Comparator.comparing(Path::getNameCount).thenComparing(Path::compareTo));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    log.debug("Requests: {}", requests);
    return requests;
}
Example 61
Project: mldht-master  File: EncoderTest.java View source code
@Test
public void testSorting() {
    Map<String, Object> root = new LinkedHashMap<>();
    String[] keys = new String[256];
    Arrays.setAll(keys, ( i) -> buf2str(ByteBuffer.wrap(new byte[] { (byte) i })));
    // clone to shuffle independently of original order
    List<String> keyList = Arrays.asList(keys);
    List<String> shuffledKeys = Arrays.asList(keys.clone());
    Collections.shuffle(shuffledKeys);
    shuffledKeys.forEach( s -> root.put(s, 1L));
    BEncoder enc = new BEncoder();
    ByteBuffer out = enc.encode(root, 2048);
    StringBuilder reference = new StringBuilder();
    reference.append("d");
    keyList.forEach( str -> {
        reference.append("1:");
        reference.append(str);
        reference.append("i1e");
    });
    reference.append("e");
    assertEquals(str2buf(reference.toString()), out);
}
Example 62
Project: earthsci-master  File: URIUtil.java View source code
@SuppressWarnings("nls")
public static Map<String, String> getParameterMap(URI uri) {
    if (Util.isEmpty(uri.getQuery())) {
        return Collections.emptyMap();
    }
    Map<String, String> result = new LinkedHashMap<String, String>();
    for (String paramPair : uri.getQuery().split("[&;]+")) {
        String[] paramComponents = paramPair.split("=");
        if (paramComponents.length > 1) {
            result.put(paramComponents[0], paramComponents[1]);
        } else if (paramComponents.length == 1) {
            result.put(paramComponents[0], null);
        }
    }
    return result;
}
Example 63
Project: platform_tools_adt_idea-master  File: RadRelativeLayoutComponent.java View source code
@Override
public boolean deleteChildren(@NotNull RadComponent parent, @NotNull List<RadComponent> deleted) {
    List<RadViewComponent> deletedComponents = RadViewComponent.getViewComponents(deleted);
    List<RadViewComponent> movedComponents = Collections.emptyList();
    RadViewComponent relativeLayout = (RadViewComponent) parent;
    final DeletionHandler handler = new DeletionHandler(deletedComponents, movedComponents, relativeLayout);
    ApplicationManager.getApplication().runWriteAction(new Runnable() {

        @Override
        public void run() {
            handler.updateConstraints();
        }
    });
    return false;
}
Example 64
Project: schach-master  File: Fingerprint.java View source code
/*
     * Gibt einen eindeutigen Fingerprint des aktuellen Spielfeldes
     * (Schachfiguren auf Brett) zurueck, um eine Situation zu identifizieren
     * 
     * @param map HashMap<Integer,Byte> mit Situation von der Fingerprint
     * erstellt werden soll
     * 
     * @return String Fingerprint als String als Format
     * "pos1,figwert1--pos2,figwert2--..."
     */
@SuppressWarnings("unchecked")
public static String getFingerprint(HashMap<Integer, Byte> map) {
    HashMap<Integer, Byte> cloneMap = (HashMap<Integer, Byte>) map.clone();
    String fingerprint = "";
    Iterator<Entry<Integer, Byte>> it = cloneMap.entrySet().iterator();
    /*
         * Da die HashMap die Eintraege unterschiedlich ausliest, ist hier die Moeglichkeit,
         * FigureValue mit position zu verknuepfen um sie dann sortieren zu koennen.
         */
    class Identifier implements Comparable {

        byte figureValue;

        int position;

        public Identifier(byte figureValue, int position) {
            this.figureValue = figureValue;
            this.position = position;
        }

        public byte getFigureValue() {
            return this.figureValue;
        }

        public int getPosition() {
            return this.position;
        }

        public int compareTo(Object id) {
            int position;
            if (id instanceof Identifier) {
                position = ((Identifier) id).getPosition();
                return (position - this.position);
            } else {
                return 0;
            }
        }
    }
    List<Identifier> id = new LinkedList<Identifier>();
    while (it.hasNext()) {
        Map.Entry<Integer, Byte> pair = (Map.Entry<Integer, Byte>) it.next();
        byte figureValue = pair.getValue();
        int position = pair.getKey().intValue();
        id.add(new Identifier(figureValue, position));
        it.remove();
    }
    //fuer einen eindeutigen Fingerprint, muss Liste sortiert werden.
    Collections.sort(id);
    while (id.size() > 0) {
        fingerprint += id.get(0).getPosition() + "," + id.get(0).getFigureValue() + "--";
        id.remove(0);
    }
    fingerprint = fingerprint.substring(0, fingerprint.length() - 2);
    return fingerprint;
}
Example 65
Project: RedReader-master  File: FilteredCommentListingManager.java View source code
private Collection<GroupedRecyclerViewAdapter.Item> filter(Collection<RedditCommentListItem> comments) {
    final Collection<RedditCommentListItem> searchComments;
    if (mSearchString == null) {
        searchComments = comments;
    } else {
        searchComments = new ArrayList<>();
        for (RedditCommentListItem comment : comments) {
            if (!comment.isComment())
                continue;
            String commentStr = comment.asComment().getParsedComment().getRawComment().body;
            if (commentStr != null) {
                commentStr = General.asciiLowercase(commentStr);
                if (commentStr.contains(mSearchString)) {
                    searchComments.add(comment);
                }
            }
        }
    }
    return Collections.<GroupedRecyclerViewAdapter.Item>unmodifiableCollection(searchComments);
}
Example 66
Project: extdirectspring-master  File: DefaultRouterExceptionHandler.java View source code
@Override
public Object handleException(MethodInfo methodInfo, BaseResponse response, Exception e, HttpServletRequest request) {
    Throwable cause;
    if (e.getCause() != null) {
        cause = e.getCause();
    } else {
        cause = e;
    }
    response.setType("exception");
    response.setMessage(this.configurationService.getConfiguration().getMessage(cause));
    if (this.configurationService.getConfiguration().isSendStacktrace()) {
        response.setWhere(ExtDirectSpringUtil.getStackTrace(cause));
    } else {
        response.setWhere(null);
    }
    if (methodInfo.isType(ExtDirectMethodType.FORM_POST) || methodInfo.isType(ExtDirectMethodType.FORM_POST_JSON)) {
        return Collections.singletonMap("success", Boolean.FALSE);
    }
    return null;
}
Example 67
Project: osmdroid-master  File: ExtraSamplesActivity.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //needed for unit tests
    MainActivity.updateStoragePrefreneces(this);
    setContentView(R.layout.activity_extra_samples);
    FragmentManager fm = this.getSupportFragmentManager();
    if (fm.findFragmentByTag(SAMPLES_FRAGMENT_TAG) == null) {
        FragmentSamples fragmentSamples = FragmentSamples.newInstance(SampleFactory.getInstance(), Collections.EMPTY_LIST);
        fm.beginTransaction().add(org.osmdroid.R.id.samples_container, fragmentSamples, SAMPLES_FRAGMENT_TAG).commit();
    }
}
Example 68
Project: jeboorker-master  File: ConverterFactory.java View source code
public static List<IEBookConverter> getConverter(IResourceHandler resource) {
    if (resource != null && JeboorkerConstants.SUPPORTED_MIMES.MIME_CBZ.getMime().equals(resource.getMimeType(true))) {
        ArrayList<IEBookConverter> result = new ArrayList<>();
        result.add(new CbzToEpubConverter(resource));
        result.add(new CbzToPdfConverter(resource));
        result.add(new CbzToCbrConverter(resource));
        result.add(new CbzToCbzConverter(resource));
        return result;
    } else if (resource != null && JeboorkerConstants.SUPPORTED_MIMES.MIME_CBR.getMime().equals(resource.getMimeType(true))) {
        ArrayList<IEBookConverter> result = new ArrayList<>();
        result.add(new CbrToEpubConverter(resource));
        result.add(new CbrToPdfConverter(resource));
        result.add(new CbrToCbzConverter(resource));
        result.add(new CbrToCbrConverter(resource));
        return result;
    } else if (resource != null && JeboorkerConstants.SUPPORTED_MIMES.MIME_PDF.getMime().equals(resource.getMimeType(true))) {
        ArrayList<IEBookConverter> result = new ArrayList<>();
        result.add(new PdfToCBZConverter(resource));
        result.add(new PdfToTxtConverter(resource));
        result.add(new PdfToPdfConverter(resource));
        return result;
    }
    return Collections.emptyList();
}
Example 69
Project: FreeBuilder-master  File: StaticExcerptTest.java View source code
@Test
public void testOrdering() {
    StaticExcerpt method1 = new DummyStaticExcerpt(METHOD, "bar");
    StaticExcerpt method2 = new DummyStaticExcerpt(METHOD, "foo");
    StaticExcerpt type1 = new DummyStaticExcerpt(TYPE, "Bar");
    StaticExcerpt type2 = new DummyStaticExcerpt(TYPE, "Foo");
    List<StaticExcerpt> excerpts = new ArrayList<>();
    excerpts.add(method2);
    excerpts.add(type1);
    excerpts.add(method1);
    excerpts.add(type2);
    Collections.sort(excerpts);
    assertThat(excerpts).containsExactly(method1, method2, type1, type2).inOrder();
}
Example 70
Project: wampspring-demos-master  File: SchedulerHandler.java View source code
@WampPublishListener(value = "schdemo#clientDoAdd", replyTo = "schdemo#serverDoAdd", excludeSender = true)
public Map<String, List<Object>> add(PublishMessage message, List<Map<String, Object>> records) {
    List<Object> updatedRecords = new ArrayList<>();
    List<Map<String, Object>> ids = new ArrayList<>();
    for (Map<String, Object> r : records) {
        @SuppressWarnings("unchecked") Map<String, Object> record = (Map<String, Object>) r.get("data");
        String internalId = (String) r.get("internalId");
        CustomEvent event = mapper.convertValue(record, CustomEvent.class);
        CustomEventDb.create(event);
        updatedRecords.add(event);
        Map<String, Object> result = new HashMap<>();
        result.put("internalId", internalId);
        result.put("record", event);
        ids.add(result);
    }
    this.eventMessenger.sendTo("schdemo#serverSyncId", Collections.singletonMap("records", ids), message.getWebSocketSessionId());
    return Collections.singletonMap("records", updatedRecords);
}
Example 71
Project: eclipselink.runtime-master  File: DefaultContentAssistExtensionTest.java View source code
/**
     * [email protected]}
     */
@Override
protected ContentAssistExtension buildContentAssistExtension() {
    return new ContentAssistExtension() {

        public Iterable<String> classNames(String prefix, ClassType type) {
            if (type == ClassType.INSTANTIABLE) {
                return filter(DefaultContentAssistExtensionTest.this.classNames(), prefix);
            }
            return filter(DefaultContentAssistExtensionTest.this.enumTypes(), prefix);
        }

        public Iterable<String> columnNames(String tableName, String prefix) {
            return Collections.emptyList();
        }

        public Iterable<String> tableNames(String prefix) {
            return Collections.emptyList();
        }
    };
}
Example 72
Project: idnadrev-master  File: ManagePostsDS.java View source code
@Override
public List<BasePost> loadModel(Consumer<List<BasePost>> furtherProcessing) {
    if (selectedBlog == null) {
        return Collections.emptyList();
    } else {
        pages.setBlog(selectedBlog);
        pages.scan();
        Comparator<BasePost> comparing = Comparator.comparing( p -> p.getHeader().getLocalDateTime().orElse(LocalDateTime.now()));
        List<BasePost> allPosts = //
        pages.getAllPosts().stream().filter(//
         p -> p != null).filter(//
         p -> p.getHeader().getTitle() != null && p.getHeader().getTitle().length() > 0).sorted(//
        comparing.reversed()).collect(Collectors.toList());
        return allPosts;
    }
}
Example 73
Project: bennu-master  File: PortalBootstrapper.java View source code
@Bootstrap
public static List<BootstrapError> bootstrapPortal(PortalSection portalSection) {
    PortalConfiguration portalConfiguration = PortalConfiguration.getInstance();
    new MenuContainer(portalConfiguration.getMenu(), ApplicationRegistry.getAppByKey("bennu-admin"));
    portalConfiguration.setApplicationCopyright(makeLocalized(portalSection.getOrganizationName()));
    portalConfiguration.setApplicationTitle(makeLocalized(portalSection.getApplicationTitle()));
    portalConfiguration.setApplicationSubTitle(makeLocalized(portalSection.getApplicationTitle()));
    portalConfiguration.setDocumentationBaseUrl(portalSection.getDocumentationUrl());
    return Collections.emptyList();
}
Example 74
Project: jentrata-msh-master  File: OutgoingPayloadList.java View source code
public List getTaskList() {
    try {
        Iterator payloads = AS2PlusProcessor.getInstance().getOutgoingPayloadRepository().getPayloadCaches().iterator();
        List tasks = new ArrayList();
        while (payloads.hasNext()) {
            try {
                PayloadCache cache = (PayloadCache) payloads.next();
                if (cache.isValid()) {
                    OutgoingPayloadTask task = new OutgoingPayloadTask(cache);
                    tasks.add(task);
                } else {
                    AS2PlusProcessor.getInstance().getLogger().error("Invalid payload cache: " + cache);
                }
            } catch (Exception e) {
                AS2PlusProcessor.getInstance().getLogger().error("Error in creating outgoing payload task", e);
            }
        }
        return tasks;
    } catch (Exception e) {
        AS2PlusProcessor.getInstance().getLogger().error("Error in retrieving outgoing payloads", e);
        return Collections.EMPTY_LIST;
    }
}
Example 75
Project: ilarkesto-master  File: GwtServiceCallGenerator.java View source code
@Override
protected void printCode(JavaPrinter out) {
    out.package_(getPackageName());
    out.beginClass(call.getValue() + "ServiceCall", "scrum.client.core.AServiceCall", null);
    List<Node> parameters = call.getChildrenByType(Parameter);
    Collections.sort(parameters, new NodeByIndexComparator());
    for (Node parameter : parameters) {
        out.field("private", getType(parameter), parameter.getValue(), null);
    }
    List<String> constructorParameters = new ArrayList<String>(parameters.size());
    for (Node parameter : parameters) {
        constructorParameters.add(getType(parameter) + " " + parameter.getValue());
    }
    out.beginConstructor(constructorParameters);
    for (Node parameter : parameters) {
        out.assignment("this." + parameter.getValue(), parameter.getValue());
    }
    out.endConstructor();
    StringBuilder callParameters = new StringBuilder();
    for (Node parameter : parameters) {
        callParameters.append(parameter.getValue()).append(", ");
    }
    out.beginMethod("void", "execute", Arrays.asList("Runnable returnHandler"));
    out.statement("serviceCaller.onServiceCall()");
    out.statement("serviceCaller.getService()." + Str.lowercaseFirstLetter(call.getValue()) + "(serviceCaller.getConversationNumber(), " + callParameters + "new DefaultCallback(returnHandler))");
    out.endMethod();
    out.toStringMethod('\"' + call.getValue() + '\"');
    out.endClass();
}
Example 76
Project: cdt-master  File: RebuildConfigurationsHandler.java View source code
/**
	 * Returns a list of CDT projects from the selection.
	 */
public static List<IProject> getSelectedCdtProjects(IStructuredSelection selection) {
    if (selection.isEmpty())
        return Collections.emptyList();
    List<IProject> projects = new ArrayList<>();
    for (Object element : selection.toArray()) {
        IProject project = null;
        if (element instanceof IProject) {
            project = (IProject) element;
        } else if (element instanceof ICProject) {
            project = ((ICProject) element).getProject();
        }
        if (project != null && CoreModel.getDefault().isNewStyleProject(project)) {
            projects.add(project);
        }
    }
    return projects;
}
Example 77
Project: eclipse.jdt.ui-master  File: OrderedRunner.java View source code
@Override
protected List<FrameworkMethod> computeTestMethods() {
    List<FrameworkMethod> methods = new ArrayList<FrameworkMethod>(super.computeTestMethods());
    Order order = getTestClass().getJavaClass().getAnnotation(Order.class);
    final List<String> orderedNames = Arrays.asList(order.value());
    Collections.sort(methods, new Comparator<FrameworkMethod>() {

        public int compare(FrameworkMethod m1, FrameworkMethod m2) {
            String n1 = m1.getName();
            String n2 = m2.getName();
            int i1 = orderedNames.indexOf(n1);
            int i2 = orderedNames.indexOf(n2);
            return i1 < i2 ? -1 : 1;
        }
    });
    return methods;
}
Example 78
Project: enviroCar-app-master  File: PIDSupportedQuirkTest.java View source code
@Test
public void testQuirkIntegration() throws IOException, StreamFinishedException {
    byte[] bytesFull = Base64.decode("QjcwN0U4MDA8vj48uBM=", Base64.DEFAULT);
    byte[] bytesFullWithEnd = Arrays.copyOf(bytesFull, bytesFull.length + 1);
    bytesFullWithEnd[bytesFullWithEnd.length - 1] = DriveDeckSportAdapter.END_OF_LINE_RESPONSE;
    PIDSupportedQuirk quirk = new PIDSupportedQuirk();
    CommandExecutor executor = new CommandExecutor(new ByteArrayInputStream(bytesFullWithEnd), new ByteArrayOutputStream(), Collections.emptySet(), DriveDeckSportAdapter.END_OF_LINE_RESPONSE, DriveDeckSportAdapter.CARRIAGE_RETURN);
    executor.setQuirk(quirk);
    byte[] bytes = executor.retrieveLatestResponse();
    Assert.assertTrue(Arrays.equals(bytes, bytesFull));
}
Example 79
Project: aws-toolkit-eclipse-master  File: TagFormatter.java View source code
/**
     * Returns a formatted string representing the tags given. They will be
     * sorted by their keys.
     */
public static String formatTags(List<Tag> tags) {
    if (tags == null || tags.isEmpty())
        return "";
    Collections.sort(tags, new Comparator<Tag>() {

        public int compare(Tag o1, Tag o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    StringBuilder allTags = new StringBuilder();
    boolean first = true;
    for (Tag tag : tags) {
        if (first) {
            first = false;
        } else {
            allTags.append("; ");
        }
        allTags.append(tag.getKey()).append("=").append(tag.getValue());
    }
    return allTags.toString();
}
Example 80
Project: virgo.kernel-master  File: HelpCommandCompleter.java View source code
/**
     * [email protected]}
     */
public List<String> getCompletionCandidates(String subCommand, String... arguments) {
    List<String> candidates = new ArrayList<String>();
    if (arguments.length == 0) {
        // only complete first argument (subCommand)
        List<CommandDescriptor> commandDescriptors = this.commandRegistry.getCommandDescriptors();
        for (CommandDescriptor commandDescriptor : commandDescriptors) {
            if (commandDescriptor.getCommandName().startsWith(subCommand)) {
                candidates.add(commandDescriptor.getCommandName());
            }
        }
    }
    Collections.sort(candidates);
    return candidates;
}
Example 81
Project: platform_packages_apps_settings-master  File: PermissionsSummaryHelper.java View source code
@Override
public void onGetAppPermissions(@NonNull List<RuntimePermissionPresentationInfo> permissions) {
    final int permissionCount = permissions.size();
    int grantedStandardCount = 0;
    int grantedAdditionalCount = 0;
    int requestedCount = 0;
    List<CharSequence> grantedStandardLabels = new ArrayList<>();
    for (int i = 0; i < permissionCount; i++) {
        RuntimePermissionPresentationInfo permission = permissions.get(i);
        requestedCount++;
        if (permission.isGranted()) {
            if (permission.isStandard()) {
                grantedStandardLabels.add(permission.getLabel());
                grantedStandardCount++;
            } else {
                grantedAdditionalCount++;
            }
        }
    }
    Collator collator = Collator.getInstance();
    collator.setStrength(Collator.PRIMARY);
    Collections.sort(grantedStandardLabels, collator);
    callback.onPermissionSummaryResult(grantedStandardCount, requestedCount, grantedAdditionalCount, grantedStandardLabels);
}
Example 82
Project: Klyph-master  File: UserMessagesRequest.java View source code
@Override
public ArrayList<GraphObject> handleResult(JSONArray[] result) {
    JSONArray data = result[0];
    JSONArray recipients = result[1];
    JSONArray user_pics = result[2];
    assocData(recipients, user_pics, "id", "id", "pic", "url");
    assocData3(data, recipients, "recipients", "id", "recipients_friends");
    UnifiedMessageDeserializer deserializer = new UnifiedMessageDeserializer();
    ArrayList<GraphObject> mts = (ArrayList<GraphObject>) deserializer.deserializeArray(data);
    Collections.reverse(mts);
    setHasMoreData(mts.size() >= 15);
    return mts;
}
Example 83
Project: schemacrawler-master  File: SchemaCrawlerSqlTypesGenerator.java View source code
private static Map<Integer, String> getJavaSqlTypes() {
    final Map<Integer, String> javaSqlTypes = new HashMap<Integer, String>();
    final Field[] staticFields = Types.class.getFields();
    for (final Field field : staticFields) {
        try {
            final String fieldName = field.getName();
            final Integer fieldValue = (Integer) field.get(null);
            javaSqlTypes.put(fieldValue, fieldName);
        } catch (final SecurityException e) {
            continue;
        } catch (final IllegalAccessException e) {
            continue;
        }
    }
    return Collections.unmodifiableMap(javaSqlTypes);
}
Example 84
Project: galen-master  File: OnFilterProcessor.java View source code
public List<StructNode> process(StringCharReader reader, StructNode statementNode) {
    String rest = reader.getTheRest().trim().trim();
    if (rest.isEmpty()) {
        throw new SyntaxException(statementNode, "Missing tags");
    }
    List<String> pageSpecTags = pageSpecHandler.getSectionFilter().getIncludedTags();
    List<String> filterTags = parseTagsFrom(rest);
    if (!containsExcludedTags(filterTags, pageSpecHandler.getSectionFilter().getExcludedTags())) {
        for (String filterTag : filterTags) {
            if (filterTag.equals("*") || (pageSpecTags != null && pageSpecTags.contains(filterTag))) {
                return statementNode.getChildNodes();
            }
        }
    }
    return Collections.emptyList();
}
Example 85
Project: heron-master  File: AllGroupingTest.java View source code
/**
   * Method: getListToSend(HeronTuples.HeronDataTuple tuple)
   */
@Test
public void testGetListToSend() throws Exception {
    List<Integer> taskIds = new LinkedList<>();
    for (int i = 0; i < 100; ++i) {
        taskIds.add(i);
    }
    AllGrouping g = new AllGrouping(taskIds);
    for (int i = 0; i < 1000; ++i) {
        HeronTuples.HeronDataTuple dummy = HeronTuples.HeronDataTuple.getDefaultInstance();
        List<Integer> dest = g.getListToSend(dummy);
        Assert.assertEquals(dest.size(), taskIds.size());
        Collections.sort(dest);
        for (int j = 0; j < taskIds.size(); ++j) {
            Assert.assertEquals(taskIds.get(j), dest.get(j));
        }
    }
}
Example 86
Project: metrics-master  File: BufferPoolMetricSet.java View source code
@Override
public Map<MetricName, Metric> getMetrics() {
    final Map<MetricName, Metric> gauges = new HashMap<MetricName, Metric>();
    for (String pool : POOLS) {
        for (int i = 0; i < ATTRIBUTES.length; i++) {
            final String attribute = ATTRIBUTES[i];
            final String name = NAMES[i];
            try {
                final ObjectName on = new ObjectName("java.nio:type=BufferPool,name=" + pool);
                mBeanServer.getMBeanInfo(on);
                gauges.put(name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute));
            } catch (JMException ignored) {
                LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6");
            }
        }
    }
    return Collections.unmodifiableMap(gauges);
}
Example 87
Project: parkandrideAPI-master  File: RequestLogKeyTest.java View source code
@Test
public void testOrderingOfList() {
    final DateTime now = DateTime.now();
    // Nulls first
    RequestLogKey first = new RequestLogKey("url", null, now);
    RequestLogKey second = new RequestLogKey("url", "aaa", now);
    RequestLogKey third = new RequestLogKey("xrl", "aaa", now);
    RequestLogKey fourth = new RequestLogKey("url", "bbb", now);
    RequestLogKey last = new RequestLogKey("url", "aaa", now.plusSeconds(1));
    final List<RequestLogKey> list = newArrayList(first, second, third, fourth, last);
    Collections.shuffle(list);
    Collections.sort(list);
    assertThat(list).containsExactly(first, second, third, fourth, last);
}
Example 88
Project: polly-master  File: RankCommand.java View source code
@Override
protected boolean executeOnBoth(User executer, String channel, Signature signature) throws CommandException, InsufficientRightsException {
    if (this.match(signature, 0)) {
        final String venadName = signature.getStringValue(0);
        List<ScoreBoardEntry> entries = this.sbeManager.getEntries(venadName);
        if (entries.isEmpty()) {
            this.reply(channel, MSG.bind(MSG.rankNoVenad, venadName));
            return false;
        }
        Collections.sort(entries, ScoreBoardEntry.BY_DATE);
        ScoreBoardEntry oldest = entries.iterator().next();
        ScoreBoardEntry youngest = entries.get(entries.size() - 1);
        long diff = Math.abs(youngest.getDate().getTime() - oldest.getDate().getTime());
        long days = Milliseconds.toDays(diff);
        int pointDiff = youngest.getPoints() - oldest.getPoints();
        double pointsPerDay = (double) pointDiff / (double) days;
        final String result = MSG.bind(MSG.rankSuccess, youngest.getRank(), youngest.getPoints(), this.getMyPolly().formatting().formatNumber(pointsPerDay), this.getMyPolly().formatting().formatTimeSpanMs(diff), this.getMyPolly().formatting().formatDate(youngest.getDate()));
        this.reply(channel, result);
    }
    return false;
}
Example 89
Project: powermock-master  File: PowerMockIgnorePackagesExtractorImpl.java View source code
@Override
public String[] getPackagesToIgnore(AnnotatedElement element) {
    List<String> ignoredPackages = new LinkedList<String>();
    PowerMockIgnore annotation = element.getAnnotation(PowerMockIgnore.class);
    if (annotation != null) {
        String[] ignores = annotation.value();
        Collections.addAll(ignoredPackages, ignores);
    }
    if (element instanceof Class<?>) {
        Class<?> klazz = (Class<?>) element;
        Class<?> superclass = klazz.getSuperclass();
        if (superclass != null && !superclass.equals(Object.class)) {
            String[] packagesToIgnore = getPackagesToIgnore(superclass);
            Collections.addAll(ignoredPackages, packagesToIgnore);
        }
    }
    return ignoredPackages.toArray(new String[ignoredPackages.size()]);
}
Example 90
Project: REST-OCD-Services-master  File: SlpaPopularityListenerRule.java View source code
@Override
public int getLabel(CustomGraph graph, Node listener, Map<Node, Integer> receivedLabels) {
    /*
		 * Creates a histogram for the label occurrences.
		 */
    Map<Integer, Double> histogram = new HashMap<Integer, Double>();
    for (Map.Entry<Node, Integer> entry : receivedLabels.entrySet()) {
        int label = entry.getValue();
        Edge edge = listener.getEdgeTo(entry.getKey());
        double influence = graph.getEdgeWeight(edge);
        if (histogram.containsKey(label)) {
            double popularity = histogram.get(label);
            histogram.put(label, popularity + influence);
        } else {
            histogram.put(label, influence);
        }
    }
    /*
		 * Derives the most frequent Label.
		 */
    double maxPopularity = Double.NEGATIVE_INFINITY;
    List<Integer> mostPopularLabels = new ArrayList<Integer>();
    for (Map.Entry<Integer, Double> entry : histogram.entrySet()) {
        double popularity = entry.getValue();
        if (popularity >= maxPopularity) {
            if (popularity > maxPopularity) {
                maxPopularity = popularity;
                mostPopularLabels.clear();
            }
            mostPopularLabels.add(entry.getKey());
        }
    }
    int chosenLabel = -1;
    if (mostPopularLabels.size() > 0) {
        /*
			 * Ensures node order does not influence label selection
			 */
        Collections.shuffle(mostPopularLabels);
        chosenLabel = mostPopularLabels.get(0);
    }
    return chosenLabel;
}
Example 91
Project: fdroidclient-master  File: QuerySelection.java View source code
public QuerySelection add(QuerySelection query) {
    String s = null;
    if (this.hasSelection() && query.hasSelection()) {
        s = " (" + this.selection + ") AND (" + query.getSelection() + ") ";
    } else if (this.hasSelection()) {
        s = this.selection;
    } else if (query.hasSelection()) {
        s = query.selection;
    }
    int thisNumArgs = this.hasArgs() ? this.args.length : 0;
    int queryNumArgs = query.hasArgs() ? query.args.length : 0;
    List<String> a = new ArrayList<>(thisNumArgs + queryNumArgs);
    if (this.hasArgs()) {
        Collections.addAll(a, this.args);
    }
    if (query.hasArgs()) {
        Collections.addAll(a, query.getArgs());
    }
    return new QuerySelection(s, a);
}
Example 92
Project: ldbc_snb_datagen-master  File: RandomKnowsGenerator.java View source code
public void generateKnows(ArrayList<Person> persons, int seed, ArrayList<Float> percentages, int step_index) {
    rand.setSeed(seed);
    ArrayList<Integer> stubs = new ArrayList<Integer>();
    int index = 0;
    for (Person p : persons) {
        long degree = Knows.target_edges(p, percentages, step_index);
        for (int i = 0; i < degree; ++i) {
            stubs.add(index);
        }
        ++index;
    }
    Collections.shuffle(stubs, rand);
    while (!stubs.isEmpty()) {
        int first = rand.nextInt(stubs.size());
        int first_index = stubs.get(first);
        stubs.remove(first);
        if (!stubs.isEmpty()) {
            int second = rand.nextInt(stubs.size());
            int second_index = stubs.get(second);
            stubs.remove(second);
            if (first_index != second_index) {
                Person p1 = persons.get(first_index);
                Person p2 = persons.get(second_index);
                Knows.createKnow(rand, p1, p2);
            }
        }
    }
}
Example 93
Project: Tank-master  File: ScriptLoader.java View source code
/**
     * @{inheritDoc
     */
@Override
protected List<Script> getEntities() {
    List<Script> scripts = new ScriptDao().findFiltered(ViewFilterType.ALL);
    Set<String> set = new HashSet<String>();
    for (Script p : scripts) {
        if (!p.getCreator().isEmpty()) {
            set.add(p.getCreator());
        }
    }
    List<String> list = new ArrayList<String>(set);
    Collections.sort(list);
    creatorList = new SelectItem[list.size() + 1];
    creatorList[0] = new SelectItem("", "All");
    for (int i = 0; i < list.size(); i++) {
        creatorList[i + 1] = new SelectItem(list.get(i), list.get(i));
    }
    return scripts;
}
Example 94
Project: goworks-master  File: TokenVocabDeclarationModelImpl.java View source code
@Override
public Collection<TokenVocabModel> resolve() {
    FileModelImpl file = getFile();
    if (file == null) {
        return Collections.emptyList();
    }
    List<TokenVocabModel> result = new ArrayList<>();
    // first try to find a grammar with this name
    PackageModelImpl packageModel = file.getPackage();
    for (FileModelImpl fileModel : packageModel.getFiles()) {
        String grammarName = fileModel.getName();
        int dot = grammarName.indexOf('.');
        if (dot >= 0) {
            grammarName = grammarName.substring(0, dot);
        }
        if (grammarName.equals(getName())) {
            result.add(fileModel.getVocabulary());
        }
    }
    return result;
}
Example 95
Project: skalli-master  File: RecommendedUpdateSitesTest.java View source code
@Test
public void testPropertyDefinitions() throws Exception {
    Map<String, Object> values = PropertyTestUtil.getValues();
    values.put(RecommendedUpdateSites.PROPERTY_ID, "test_updatesite");
    values.put(RecommendedUpdateSites.PROPERTY_USERID, "jon");
    values.put(RecommendedUpdateSites.PROPERTY_NAME, "Test Updatesite");
    values.put(RecommendedUpdateSites.PROPERTY_SHORT_NAME, "alias");
    values.put(RecommendedUpdateSites.PROPERTY_DESCIPTION, "This test Updatesite ist for test purpose.");
    List<UpdateSite> updateSites = new ArrayList<UpdateSite>();
    updateSites.add(createUpdateSite("1"));
    updateSites.add(createUpdateSite("2"));
    values.put(RecommendedUpdateSites.PROPERTY_UPDATESITES, updateSites);
    Map<Class<?>, String[]> requiredProperties = Collections.emptyMap();
    PropertyTestUtil.checkPropertyDefinitions(RecommendedUpdateSites.class, requiredProperties, values);
}
Example 96
Project: appengine-java-vm-runtime-master  File: ReflectionServlet.java View source code
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    // This returns a private class, Collections$2.
    Enumeration<?> e = Collections.enumeration(Collections.emptyList());
    try {
        // However, we should still be able to access the public
        // Enumeration methods reflectively.
        Method m = e.getClass().getMethod("hasMoreElements");
        m.setAccessible(true);
        Object result = m.invoke(e);
        res.getWriter().println("hasMoreElements = " + result);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}
Example 97
Project: sql-layer-master  File: DropTablesInNewSessionIT.java View source code
@Test
public void test() {
    int c = createTable("schema", "customers", "cid int not null primary key, name varchar(32)");
    int o = createTable("schema", "orders", "oid int not null primary key, cid int not null, placed date", akibanFK("cid", "customers", "cid"));
    TableName groupName = getTable(c).getGroup().getName();
    createLeftGroupIndex(groupName, "name_placed", "customers.name", "orders.placed");
    writeRow(c, 1, "bob");
    writeRow(o, 11, 1, "2012-01-01");
    Collection<String> indexesToUpdate = Collections.singleton("name_placed");
    ddl().updateTableStatistics(session(), TableName.create("schema", "customers"), indexesToUpdate);
    Session session = serviceManager().getSessionService().createSession();
    try {
        dropAllTables(session);
    } finally {
        session.close();
    }
}
Example 98
Project: TFC2-master  File: SiteList.java View source code
public Rectangle getSitesBounds() {
    if (_sorted == false && _sites != null) {
        Collections.sort(_sites, new Site());
        _currentIndex = 0;
        _sorted = true;
    }
    double xmin, xmax, ymin, ymax;
    if (_sites.size() == 0) {
        return new Rectangle(0, 0, 0, 0);
    }
    xmin = Integer.MAX_VALUE;
    xmax = Integer.MIN_VALUE;
    for (int i = 0; i < _sites.size(); ++i) {
        Site site = _sites.get(i);
        if (site.getX() < xmin) {
            xmin = site.getX();
        }
        if (site.getX() > xmax) {
            xmax = site.getX();
        }
    }
    // here's where we assume that the sites have been sorted on y:
    ymin = _sites.get(0).getY();
    ymax = _sites.get(_sites.size() - 1).getY();
    Rectangle out = new Rectangle();
    out.setFrame(xmin, ymin, xmax - xmin, ymax - ymin);
    return out;
}
Example 99
Project: pentaho-kettle-master  File: KettleReportBuilderTest.java View source code
@Test
public void createReport() throws Exception {
    LoggingObjectInterface log = mock(LoggingObjectInterface.class);
    AutoDocOptionsInterface options = mock(AutoDocOptionsInterface.class);
    when(options.isIncludingImage()).thenReturn(Boolean.TRUE);
    KettleReportBuilder builder = new KettleReportBuilder(log, Collections.<ReportSubjectLocation>emptyList(), "", options);
    builder.createReport();
    assertNotNull(builder.getReport());
    assertNotNull(builder.getReport().getDataFactory());
    assertNotNull(builder.getReport().getReportHeader());
    assertNotNull(builder.getReport().getReportFooter());
    assertNotNull(builder.getReport().getRootGroup());
    assertNotNull(builder.getReport().getPageDefinition());
    assertTrue(builder.getReport().getExpressions().size() > 0);
}
Example 100
Project: framework-master  File: GridRendererChangeTest.java View source code
@Test
public void testChangeRenderer() {
    setDebug(true);
    openTestURL();
    GridCellElement cell = $(GridElement.class).first().getCell(0, 0);
    assertTrue("No button in the first cell.", cell.isElementPresent(By.tagName("button")));
    int width = cell.getSize().getWidth();
    List<ButtonElement> buttons = $(ButtonElement.class).all();
    Collections.reverse(buttons);
    // Order: TextRenderer, HTMLRenderer, ButtonRenderer
    for (ButtonElement button : buttons) {
        button.click();
        assertNoErrorNotifications();
        cell = $(GridElement.class).first().getCell(0, 0);
        assertEquals("Cell size changed", width, cell.getSize().getWidth());
    }
    assertTrue("No button in the first cell.", cell.isElementPresent(By.tagName("button")));
}
Example 101
Project: platform_tools_motodev-master  File: ToolsCountries.java View source code
/**
     * Returns all countries.
     * 
     * @return All countries.
     */
public List<Country> getCountries() {
    List<Country> toReturn = new ArrayList<Country>();
    try {
        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()) {
            String countryCode = keys.nextElement();
            String countryName = bundle.getString(countryCode);
            toReturn.add(new Country(countryCode, countryName));
        }
        Collections.sort(toReturn);
    } catch (MissingResourceException e) {
        toReturn = new ArrayList<Country>();
    }
    return toReturn;
}