Example usage for java.util TreeSet size

List of usage examples for java.util TreeSet size

Introduction

In this page you can find the example usage for java.util TreeSet size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:edu.fullerton.timeseriesapp.TimeSeriesApp.java

private HashSet<Integer> getSelections() throws SQLException, LdvTableException, ViewConfigException {
    HashSet<Integer> ret = new HashSet<>();
    long strt = System.currentTimeMillis();
    getDbTables();/*from   w w w  .ja v  a  2s.c o  m*/

    {
        int n;
        if (channelNames == null || channelNames.length == 0) {
            throw new IllegalArgumentException("No Channel specified");
        }
        if ((server == null || server.isEmpty()) && (cType == null || cType.isEmpty())) {
            for (String channelName : channelNames) {
                n = chanTbl.getBestMatch(channelName);
                ret.add(n);
            }
        } else {
            if (cType == null || cType.isEmpty()) {
                cType = "raw";
            }
            for (String channelName : channelNames) {
                TreeSet<ChanInfo> chSet = chanTbl.getAsSet(server, channelName, cType, 10);
                if (chSet.size() > 1) {
                    System.err.println("Warning: more than one channel matches: " + channelName);
                }

                for (ChanInfo ci : chSet) {
                    Integer id = ci.getId();
                    ret.add(id);
                }
            }
        }
        if (ret.isEmpty()) {
            for (String channelName : channelNames) {
                System.err.println("Channel requested was not found: " + channelName);
            }
        }
    }
    return ret;

}

From source file:com.antelink.sourcesquare.client.scan.SourceSquareFSWalker.java

public synchronized void queryFiles(TreeSet<File> fileSet) throws InterruptedException {
    HashMap<String, String> toAnalyze = new HashMap<String, String>();
    Iterator<File> iterator = fileSet.iterator();
    logger.debug(fileSet.size() + " files to analyze");
    long count = 0;
    long timer = System.currentTimeMillis();
    while (iterator.hasNext()) {

        File file = iterator.next();
        logger.trace("adding analyze file to the pool: " + file.getAbsolutePath());
        try {/*from www .jav a2 s. com*/
            String sha1 = FileAnalyzer.calculateHash("SHA-1", file);
            toAnalyze.put(file.getAbsolutePath(), sha1);
            count++;
        } catch (Exception e) {
            logger.error("skipping files " + file, e);
        }

        if (toAnalyze.size() == this.filePerQuery || System.currentTimeMillis() - timer > COMPUTE_WAIT_TIME) {
            // dispatch analysis
            timer = System.currentTimeMillis();
            analyzeMap(toAnalyze);
            this.filePerQuery = Math.min(MAX_FILE_PER_QUERY, this.filePerQuery * 2);
            logger.trace("new counter: " + count);

        }
    }
    analyzeMap(toAnalyze);

    while (!allProcessDone()) {
        synchronized (this.lock) {
            this.lock.wait();
        }

    }
    this.eventBus.fireEvent(new ScanCompleteEvent(this.levels));

    logger.info("Analysis done " + count);
}

From source file:net.certiv.authmgr.task.section.model.AnalyzeModel.java

private void analyzePartitions(PersistantWordsDataSource pds, String category,
        HashMap<String, HashMap<String, WordProbabilityPT>> partsMap) {

    PartitionKeyComparator keyComp = new PartitionKeyComparator(partsMap);
    TreeSet<String> partKeys = new TreeSet<String>(keyComp);
    partKeys.addAll(partsMap.keySet());//from ww  w.  j a v  a2  s.c  o  m

    String partitions = "";
    for (Iterator<String> it = partKeys.iterator(); it.hasNext();) {
        partitions = partitions + it.next() + " ";
    }
    Log.info(this, "Partition collection: " + partKeys.size() + " = " + partitions);

    // for each partition
    for (Iterator<String> it = partKeys.iterator(); it.hasNext();) {
        String partition = it.next();
        HashMap<String, WordProbabilityPT> wordsMap = partsMap.get(partition);
        analyzeWords(category, partition, wordsMap);
    }
}

From source file:org.eclipse.skalli.view.ext.impl.internal.infobox.ProjectMavenBox.java

@Override
public Component getContent(Project project, ExtensionUtil util) {
    Layout layout = new CssLayout();
    layout.addStyleName(STYLE_MAVEN_INFOBOX);
    layout.setSizeFull();/*from   w  w w.  ja  v a2 s .  c o m*/

    boolean rendered = false;
    String groupId = null;
    MavenReactorProjectExt reactorExt = project.getExtension(MavenReactorProjectExt.class);
    if (reactorExt != null) {
        MavenReactor mavenReactor = reactorExt.getMavenReactor();
        if (mavenReactor != null) {
            MavenCoordinate coordinate = mavenReactor.getCoordinate();
            groupId = coordinate.getGroupId();
            createLabel(layout, "GroupId: <b>" + groupId + "</b>");//$NON-NLS-1$ //$NON-NLS-2$
            createLabel(layout, "ArtifactId: <b>" + coordinate.getArtefactId() + "</b>");//$NON-NLS-1$ //$NON-NLS-2$
            TreeSet<MavenModule> modules = mavenReactor.getModules();
            StringBuilder sb = new StringBuilder();

            if (modules.size() > 0) {
                int lineLength = 0;
                for (MavenModule module : modules) {
                    //create popup with xml snippet
                    sb.append("<dependency>\n");
                    sb.append("    <artifactId>" + module.getArtefactId() + "</artifactId>\n");
                    sb.append("    <groupId>" + module.getGroupId() + "</groupId>\n");
                    String latestVersion = module.getLatestVersion();
                    if (StringUtils.isNotBlank(latestVersion)) {
                        sb.append("    <version>" + latestVersion + "</version>\n");
                    } else {
                        sb.append("    <!--<version>0.0.0</version>-->\n");
                    }
                    String packaging = module.getPackaging();
                    if (StringUtils.isNotBlank(packaging)) {
                        sb.append("    <type>" + packaging + "</type>\n");
                    }
                    sb.append("</dependency>\n");
                    lineLength = calculateLineLength(module, lineLength);
                }

                final Label label = new Label(sb.toString(), Label.CONTENT_PREFORMATTED);
                //add a buffer 10, as we didn't calculate the length of surrounding strings.
                label.setWidth(lineLength + 10, Sizeable.UNITS_EM);

                PopupView.Content content = new PopupView.Content() {
                    private static final long serialVersionUID = -8362267064485433525L;

                    @Override
                    public String getMinimizedValueAsHTML() {
                        return "Modules";
                    }

                    @Override
                    public Component getPopupComponent() {
                        return label;
                    }
                };

                PopupView popup = new PopupView(content);
                popup.setHideOnMouseOut(false);
                popup.addStyleName(STYLE_MODULE_POPUP);
                layout.addComponent(popup);
            }
            rendered = true;
        }
    }
    MavenProjectExt mavenExt = project.getExtension(MavenProjectExt.class);
    if (mavenExt != null) {
        if (groupId == null) {
            groupId = mavenExt.getGroupID();
            if (StringUtils.isNotBlank(groupId)) {
                createLabel(layout, "GroupId: <b>&nbsp;" + groupId + "</b>");//$NON-NLS-1$ //$NON-NLS-2$
                rendered = true;
            }
        }
        DevInfProjectExt devInf = project.getExtension(DevInfProjectExt.class);
        if (devInf != null) {
            String reactorPomUrl = getReactorPomUrl(project, devInf, mavenExt);
            if (reactorPomUrl == null) {
                String reactorPomPath = mavenExt.getReactorPOM();
                String caption = MessageFormat.format("Reactor POM Path: {0} (relative to SCM root location)",
                        StringUtils.isNotBlank(reactorPomPath) ? reactorPomPath : "/");
                createLabel(layout, caption);
            } else {
                createLink(layout, "Reactor POM", reactorPomUrl);
            }
            rendered = true;
        }
        if (StringUtils.isNotBlank(mavenExt.getSiteUrl())) {
            createLink(layout, "Project Site", mavenExt.getSiteUrl());
            rendered = true;
        }
    }
    if (!rendered) {
        createLabel(layout, "Maven extension added but no data maintained.");
    }
    return layout;
}

From source file:org.wso2.andes.kernel.slot.SlotManagerStandalone.java

/**
 * {@inheritDoc}// w  ww  . j  a v  a2s  .  c o  m
 */
@Override
public long getSafeZoneLowerBoundId(String queueName) throws AndesException {
    long lowerBoundId = -1;
    String lockKey = queueName + SlotManagerStandalone.class;
    synchronized (lockKey.intern()) {
        TreeSet<Long> messageIDSet = slotIDMap.get(queueName);
        //set the lower bound Id for safety delete region as the safety slot count interval upper bound id + 1
        if (messageIDSet.size() >= safetySlotCount) {
            lowerBoundId = messageIDSet.toArray(new Long[messageIDSet.size()])[safetySlotCount - 1] + 1;
            // Inform the slot manager regarding the current expiry deletion range and queue.
            setDeletionTaskState(queueName, lowerBoundId);
        }
    }
    return lowerBoundId;
}

From source file:com.taobao.common.tfs.impl.LocalKey.java

private void checkOverlap(SegmentInfo segmentInfo, List<SegmentInfo> gcSegmentList) {
    TreeSet<SegmentInfo> headInfoSet = (TreeSet<SegmentInfo>) (segmentInfoSet.headSet(segmentInfo));
    if (headInfoSet.size() != 0) {
        SegmentInfo endInfo = headInfoSet.last();
        // overlap, gc
        if (endInfo.getOffset() + endInfo.getLength() > segmentInfo.getOffset()) {
            gcSegmentList.add(endInfo);/*from w w  w.j a va2s. c  o m*/
        }
    }
}

From source file:evaluation.Evaluator.java

/**
 * This function removes duplicates from an array of given labels. It is used while
 * reading the file with the predicted labels.
 *
 * @param labels    the array with the labels to be checked for duplicates
 *///  w w  w . j  a v a  2 s  . c  o  m
public String[] removeDuplicates(String labels[]) {
    TreeSet aset = new TreeSet();
    aset.addAll(Arrays.asList(labels));

    int num_of_labels = aset.size();

    String finallabels[] = new String[num_of_labels];
    Iterator iterator = aset.iterator();
    int k = 0;
    while (iterator.hasNext()) {
        finallabels[k++] = (String) iterator.next();
    }

    return finallabels;
}

From source file:com.basho.riak.client.http.util.logging.ConcurrentLoggingTest.java

/**
 * Test method for/*from w ww  .j  ava 2s.  c  o m*/
 * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)}
 * .
 * 
 * @throws InterruptedException
 */
@Test
public void retry_concurrentLogAndDump() throws InterruptedException {
    // create a bunch of threads
    // each must log 10 statements and call flush
    // ALL the statements must be present BUT ONCE in
    // the mock delegate appender (order does not matter)
    final int numThreads = 10;
    final LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler();
    ExecutorService es = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads);

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch dumpLatch = new CountDownLatch(10);

    for (int i = 0; i < numThreads; i++) {
        final int threadCounter = i;
        tasks.add(new Callable<Void>() {

            @Override
            public Void call() {
                Logger logger = Logger.getLogger("httpclient.wire");
                try {
                    startLatch.await();

                    for (int j = 0; j < 10; j++) {
                        logger.debug(String.format(MESSAGE, new Object[] { threadCounter, j }));
                    }

                    dumpLatch.countDown();
                    dumpLatch.await();

                    handler.retryMethod(new GetMethod(), new NoHttpResponseException(), 0);

                    return null;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    startLatch.countDown();
    es.invokeAll(tasks);

    verify(mockLogger, times(100)).callAppenders(logEventCaptor.capture());

    TreeSet<Integer> check = new TreeSet<Integer>();

    for (LoggingEvent le : logEventCaptor.getAllValues()) {
        // verify that each of Thread:Iter is present for 0-90-9
        int loc = Integer.parseInt(le.getMessage().toString());
        check.add(loc);
    }

    assertEquals(100, check.size());
    assertEquals(0, (int) check.first());
    assertEquals(99, (int) check.last());
}

From source file:br.bireme.mlts.MoreLikeThatServlet.java

/**
 * Processes requests for both HTTP//from   w w w. ja va2s  .c  o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest2(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        final String content = request.getParameter("content");
        final String fieldsName = request.getParameter("fieldsName");
        final String getDocument = request.getParameter("getDocument");

        if (content == null) {
            throw new ServletException("missing 'content' parameter");
        }
        if (fieldsName == null) {
            throw new ServletException("missing 'fieldsName' parameter");
        }
        final String[] fldsName = fieldsName.trim().split(" *, *");
        final boolean getDocContent = (getDocument == null) ? false : Boolean.parseBoolean(getDocument);
        final StringReader reader = new StringReader(content);
        final TreeSet<MoreLikeThat.DocX> docs = mlt.moreLikeThat(reader, fldsName, getDocContent);
        final int size = docs.size();
        int cur = 0;

        if (size == 1) {
            out.println("{");
        } else {
            out.println("{ [");
        }
        for (MoreLikeThat.DocX doc : docs) {
            final List<String> _ids = doc.doc.get("id");
            final String _id = ((_ids == null) || (_ids.isEmpty()) ? Integer.toString(doc.id) : _ids.get(0));
            out.print("    {\"id\" : ");
            out.print(_id);
            out.print(", \"score\" : ");
            out.print(Float.toString(doc.qscore));
            if (getDocContent) {
                final int msize = doc.doc.size();
                int mcur = 0;

                out.print(", \"doc\" : {");
                for (Map.Entry<String, List<String>> entry : doc.doc.entrySet()) {
                    final List<String> list = entry.getValue();
                    final int lSize = list.size();
                    int lcur = 0;

                    out.print("\"");
                    out.print(entry.getKey());
                    out.print("\" : ");
                    if (lSize > 1) {
                        out.print("[");
                    }
                    for (String con : list) {
                        out.print("\"");
                        out.print(con);
                        out.print("\"");
                        if (++lcur < lSize) {
                            out.print(", ");
                        }
                    }
                    if (lSize > 1) {
                        out.print("]");
                    }
                    if (++mcur < msize) {
                        out.print(", ");
                    }
                }
                out.print("}");
            }
            if (++cur < size) {
                out.println("},");
            } else {
                out.println("}");
            }
        }
        if (size == 1) {
            out.println("}");
        } else {
            out.println("] }");
        }
    } finally {
        out.close();
    }
}