Example usage for java.util TreeSet TreeSet

List of usage examples for java.util TreeSet TreeSet

Introduction

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

Prototype

public TreeSet() 

Source Link

Document

Constructs a new, empty tree set, sorted according to the natural ordering of its elements.

Usage

From source file:org.openmrs.module.clinicalsummary.web.controller.search.AutocompleteSearchController.java

@RequestMapping(value = "/module/clinicalsummary/search/autocompleteLocation", method = RequestMethod.GET)
public @ResponseBody Collection<String> searchLocation(
        final @RequestParam(required = true, value = "term") String nameFragment) {
    Collection<String> names = new TreeSet<String>();
    Collection<Location> locations = Context.getLocationService().getLocations(nameFragment);
    for (Location location : locations)
        names.add(location.getName());/*from   w ww.ja va  2  s. c  o m*/
    return names;
}

From source file:Main.java

public SortedListModel() {
    model = new TreeSet<Object>();
    ListDataListener lis = new ListDataListener() {
        @Override// w w w  . jav a 2 s  .  c  o m
        public void contentsChanged(ListDataEvent arg0) {
        }

        @Override
        public void intervalAdded(ListDataEvent arg0) {
        }

        @Override
        public void intervalRemoved(ListDataEvent arg0) {
        }
    };
    super.addListDataListener(lis);
    super.removeListDataListener(lis);
}

From source file:Main.java

public SortedListModel() {
    model = new TreeSet<Object>();
    ListDataListener lis = new ListDataListener() {
        @Override//from  w ww.  jav a 2 s.c o  m
        public void contentsChanged(ListDataEvent arg0) {
        }

        @Override
        public void intervalAdded(ListDataEvent arg0) {
        }

        @Override
        public void intervalRemoved(ListDataEvent arg0) {
        }
    };
    super.addListDataListener(lis);
    ListDataListener[] ldls = getListDataListeners();
    super.removeListDataListener(lis);
}

From source file:Main.java

public SortedListModel() {
    model = new TreeSet<Object>();
    ListDataListener lis = new ListDataListener() {
        @Override//from   w w w  .  ja v  a 2s  .  c o  m
        public void contentsChanged(ListDataEvent arg0) {
        }

        @Override
        public void intervalAdded(ListDataEvent arg0) {
        }

        @Override
        public void intervalRemoved(ListDataEvent arg0) {
        }
    };
    super.addListDataListener(lis);
    ListDataListener[] ldls = (ListDataListener[]) (getListeners(ListDataListener.class));
    super.removeListDataListener(lis);
}

From source file:am.ik.categolj2.domain.model.CategoryTest.java

@Test
public void testInTreeSet() {
    Category c1 = new Category(1, 1, "Programmming");
    Category c2 = new Category(1, 2, "Java");
    Category c3 = new Category(1, 3, "org");
    Category c4 = new Category(2, 4, "springframework");
    Category c5 = new Category(1, 5, "core");
    SortedSet<Category> categories = new TreeSet<Category>();

    // added randomly
    categories.add(c3);/* w  w w  . j av  a 2s  .co  m*/
    categories.add(c1);
    categories.add(c5);
    categories.add(c2);
    categories.add(c4);

    Iterator<Category> iterator = categories.iterator();

    assertThat(iterator.next(), is(c1));
    assertThat(iterator.next(), is(c2));
    assertThat(iterator.next(), is(c3));
    assertThat(iterator.next(), is(c4));
    assertThat(iterator.next(), is(c5));
}

From source file:com.opensourcestrategies.financials.accounts.GLAccountInTree.java

/**
 * Creates a new <code>GLAccountInTree</code> instance.
 *
 * @param delegator a <code>Delegator</code> value
 * @param glAccountId the GL account ID//  ww  w.j  a v a  2  s .  com
 * @param balance a <code>BigDecimal</code> value
 * @exception GenericEntityException if an error occurs
 */
public GLAccountInTree(Delegator delegator, String glAccountId, BigDecimal balance)
        throws GenericEntityException {
    super(delegator, glAccountId, balance);
    this.childAccounts = new TreeSet<GLAccountInTree>();
}

From source file:com.ricemap.spateDB.core.PrismNN.java

public TOPK(int k) {
    heap = new TreeSet<PrismNN>();
    this.k = k;
}

From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java

public static void main(String[] args) {

    if (args.length != 4) {
        System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n"
                + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n"
                + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n");
    } else {//from   www. j  a v a  2s .c  o m

        BufferedWriter outBuff = null;

        try {

            File inFile = new File(args[0]);
            File fastaFile = new File(args[1]);
            File outFile = new File(args[2]);
            File blastFile = new File(args[3]);

            //Primero cargo todos los datos del archivo xml del blast
            BufferedReader buffReader = new BufferedReader(new FileReader(blastFile));
            StringBuilder stBuilder = new StringBuilder();
            String line = null;

            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }

            buffReader.close();
            System.out.println("Creating blastoutput...");
            BlastOutput blastOutput = new BlastOutput(stBuilder.toString());
            System.out.println("BlastOutput created! :)");
            stBuilder.delete(0, stBuilder.length());

            HashMap<String, String> blastProteinsMap = new HashMap<String, String>();
            ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations();
            for (Iteration iteration : iterations) {
                blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString());
            }
            //freeing some memory
            blastOutput = null;
            //------------------------------------------------------------------------

            //Initializing writer for output file
            outBuff = new BufferedWriter(new FileWriter(outFile));

            //reading gene annotation xml file.....
            buffReader = new BufferedReader(new FileReader(inFile));
            stBuilder = new StringBuilder();
            line = null;
            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }
            buffReader.close();

            XMLElement genesXML = new XMLElement(stBuilder.toString());
            //freeing some memory I don't need anymore
            stBuilder.delete(0, stBuilder.length());

            //reading file with the reference proteins set
            ArrayList<String> proteinsReferenceSet = new ArrayList<String>();
            buffReader = new BufferedReader(new FileReader(fastaFile));
            while ((line = buffReader.readLine()) != null) {
                if (line.charAt(0) == '>') {
                    proteinsReferenceSet.add(line.split("\\|")[1]);
                }
            }
            buffReader.close();

            Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME);

            List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME);

            System.out.println("There are " + contigs.size() + " contigs to be checked... ");

            outBuff.write("There are " + contigs.size() + " contigs to be checked... \n");
            outBuff.write("Proteins reference set: \n");
            for (String st : proteinsReferenceSet) {
                outBuff.write(st + ",");
            }
            outBuff.write("\n");

            for (Element elem : contigs) {
                ContigXML contig = new ContigXML(elem);

                //escribo el id del contig en el que estoy
                outBuff.write("Checking contig: " + contig.getId() + "\n");
                outBuff.flush();

                List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME);
                System.out.println("geneList.size() = " + geneList.size());

                int numeroDeGenesParaAnalizar = geneList.size() / FACTOR;
                if (numeroDeGenesParaAnalizar == 0) {
                    numeroDeGenesParaAnalizar++;
                }

                ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>();

                outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: "
                        + numeroDeGenesParaAnalizar + "\n");

                for (int j = 0; j < numeroDeGenesParaAnalizar; j++) {
                    int geneIndex;

                    boolean geneIsDismissed = false;
                    do {
                        geneIsDismissed = false;
                        geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size()));
                        PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement());
                        if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) {
                            geneIsDismissed = true;
                        }
                    } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed);

                    indicesUtilizados.add(geneIndex);
                    System.out.println("geneIndex = " + geneIndex);

                    //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad
                    PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement());

                    outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: "
                            + gene.getAnnotationUniprotId() + "\n");
                    outBuff.write("eValue: " + gene.getEvalue() + "\n");

                    //--------------PETICION POST HTTP BLAST----------------------
                    PostMethod post = new PostMethod(BLAST_URL);
                    post.addParameter("program", "blastx");
                    post.addParameter("sequence", gene.getSequence());
                    post.addParameter("database", "uniprotkb");
                    post.addParameter("email", "ppareja@era7.com");
                    post.addParameter("exp", "1e-10");
                    post.addParameter("stype", "dna");

                    // execute the POST
                    HttpClient client = new HttpClient();
                    int status = client.executeMethod(post);
                    System.out.println("status post = " + status);
                    InputStream inStream = post.getResponseBodyAsStream();

                    String fileName = "jobid.txt";
                    FileOutputStream outStream = new FileOutputStream(new File(fileName));
                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //Once the file is created I just have to read one line in order to extract the job id
                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    String jobId = buffReader.readLine();
                    buffReader.close();

                    System.out.println("jobId = " + jobId);

                    //--------------HTTP CHECK JOB STATUS REQUEST----------------------
                    GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId);
                    String jobStatus = "";
                    do {

                        try {
                            Thread.sleep(1000);//sleep for 1000 ms                                
                        } catch (InterruptedException ie) {
                            //If this thread was intrrupted by nother thread
                        }

                        status = client.executeMethod(get);
                        //System.out.println("status get = " + status);

                        inStream = get.getResponseBodyAsStream();

                        fileName = "jobStatus.txt";
                        outStream = new FileOutputStream(new File(fileName));

                        while ((len = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        outStream.close();

                        //Once the file is created I just have to read one line in order to extract the job id
                        buffReader = new BufferedReader(new FileReader(new File(fileName)));
                        jobStatus = buffReader.readLine();
                        //System.out.println("jobStatus = " + jobStatus);
                        buffReader.close();

                    } while (!jobStatus.equals(FINISHED_JOB_STATUS));

                    //Once I'm here the blast should've already finished

                    //--------------JOB RESULTS HTTP REQUEST----------------------
                    get = new GetMethod(JOB_RESULT_URL + jobId + "/out");

                    status = client.executeMethod(get);
                    System.out.println("status get = " + status);

                    inStream = get.getResponseBodyAsStream();

                    fileName = "jobResults.txt";
                    outStream = new FileOutputStream(new File(fileName));

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //--------parsing the blast results file-----

                    TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>();

                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    while ((line = buffReader.readLine()) != null) {
                        if (line.length() > 3) {
                            String prefix = line.substring(0, 3);
                            if (prefix.equals("TR:") || prefix.equals("SP:")) {
                                String[] columns = line.split(" ");
                                String id = columns[1];
                                //System.out.println("id = " + id);

                                String e = "";

                                String[] arraySt = line.split("\\.\\.\\.");
                                if (arraySt.length > 1) {
                                    arraySt = arraySt[1].trim().split(" ");
                                    int contador = 0;
                                    for (int k = 0; k < arraySt.length && contador <= 2; k++) {
                                        String string = arraySt[k];
                                        if (!string.equals("")) {
                                            contador++;
                                            if (contador == 2) {
                                                e = string;
                                            }
                                        }

                                    }
                                } else {
                                    //Number before e-
                                    String[] arr = arraySt[0].split("e-")[0].split(" ");
                                    String numeroAntesE = arr[arr.length - 1];
                                    String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0];
                                    e = numeroAntesE + "e-" + numeroDespuesE;
                                }

                                double eValue = Double.parseDouble(e);
                                //System.out.println("eValue = " + eValue);
                                GeneEValuePair g = new GeneEValuePair(id, eValue);
                                featuresBlast.add(g);
                            }
                        }
                    }

                    GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(),
                            gene.getEvalue());

                    System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id);
                    System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue);
                    boolean blastContainsGene = false;
                    for (GeneEValuePair geneEValuePair : featuresBlast) {
                        if (geneEValuePair.id.equals(currentGeneEValuePair.id)) {
                            blastContainsGene = true;
                            //le pongo la e que tiene en el wu-blast para poder comparar
                            currentGeneEValuePair.eValue = geneEValuePair.eValue;
                            break;
                        }
                    }

                    if (blastContainsGene) {
                        outBuff.write("The protein was found in the WU-BLAST result.. \n");
                        //Una vez que se que esta en el blast tengo que ver que sea la mejor
                        GeneEValuePair first = featuresBlast.first();
                        outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id
                                + " , " + first.eValue + "\n");
                        if (first.id.equals(currentGeneEValuePair.id)) {
                            outBuff.write("Proteins with best eValue match up \n");
                        } else {
                            if (first.eValue == currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has the same eValue \n");
                            } else if (first.eValue > currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has a worse eValue :) \n");
                            } else {
                                outBuff.write(
                                        "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n");
                                //System.exit(-1);
                                if (proteinsReferenceSet.contains(first.id)) {
                                    //The protein is in the reference set and that shouldn't happen
                                    outBuff.write(
                                            "The protein was found on the reference set, checking if it belongs to the same contig...\n");
                                    String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId());
                                    if (iterationSt != null) {
                                        outBuff.write(
                                                "The protein was found in the BLAST used at the beginning of the annotation process.\n");
                                        Iteration iteration = new Iteration(iterationSt);
                                        ArrayList<Hit> hits = iteration.getIterationHits();
                                        boolean contigFound = false;
                                        Hit errorHit = null;
                                        for (Hit hit : hits) {
                                            if (hit.getHitDef().indexOf(contig.getId()) >= 0) {
                                                contigFound = true;
                                                errorHit = hit;
                                                break;
                                            }
                                        }
                                        if (contigFound) {
                                            outBuff.write(
                                                    "ERROR: A hit from the same contig was find in the Blast file: \n"
                                                            + errorHit.toString() + "\n");
                                        } else {
                                            outBuff.write("There is no hit with the same contig! :)\n");
                                        }
                                    } else {
                                        outBuff.write(
                                                "The protein is NOT in the BLAST used at the beginning of the annotation process.\n");
                                    }

                                } else {
                                    //The protein was not found on the reference set so everything's ok
                                    outBuff.write(
                                            "The protein was not found on the reference, everything's ok :)\n");
                                }
                            }
                        }

                    } else {
                        outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n");

                        //System.exit(-1);
                    }

                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //closing outputfile
                outBuff.close();
            } catch (IOException ex) {
                Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}

From source file:org.sventon.cache.direntrycache.DirEntryCacheUpdaterTest.java

@Test
public void testUpdate() throws Exception {
    final RepositoryService serviceMock = mock(RepositoryService.class);
    assertEquals(0, entryCache.getSize());

    final List<LogEntry> logEntries = new ArrayList<LogEntry>();
    final SortedSet<ChangedPath> changedPaths1 = new TreeSet<ChangedPath>();
    changedPaths1.add(new ChangedPath("/file1.java", null, -1, ChangeType.MODIFIED));
    changedPaths1.add(new ChangedPath("/file2.abc", null, -1, ChangeType.ADDED));
    changedPaths1.add(new ChangedPath("/trunk/file3.def", null, -1, ChangeType.REPLACED));
    logEntries.add(createLogEntry(123, "author", new Date(), "Log message for revision 123.", changedPaths1));

    final SortedSet<ChangedPath> changedPaths2 = new TreeSet<ChangedPath>();
    changedPaths2.add(new ChangedPath("/branch", "/trunk", 123, ChangeType.ADDED));
    changedPaths2.add(new ChangedPath("/trunk/file3.def", null, -1, ChangeType.DELETED));
    logEntries.add(createLogEntry(124, "author", new Date(), "Log message for revision 124.", changedPaths2));

    final ConfigDirectory configDirectory = TestUtils.getTestConfigDirectory();
    configDirectory.setCreateDirectories(false);
    final MockServletContext servletContext = new MockServletContext();
    servletContext.setContextPath("sventon-test");
    configDirectory.setServletContext(servletContext);
    final Application application = new Application(configDirectory);

    when(serviceMock.getLatestRevision(null)).thenReturn(124L);

    when(serviceMock.getEntryInfo(null, "/file1.java", 123))
            .thenReturn(new DirEntry("/", "file1.java", "author", new Date(), DirEntry.Kind.FILE, 123, 12345));

    when(serviceMock.getEntryInfo(null, "/file2.abc", 123))
            .thenReturn(new DirEntry("/", "file2.abc", "author", new Date(), DirEntry.Kind.FILE, 123, 12345));

    when(serviceMock.getEntryInfo(null, "/trunk/file3.def", 123)).thenReturn(
            new DirEntry("/trunk", "file3.def", "author", new Date(), DirEntry.Kind.FILE, 123, 12345));

    when(serviceMock.getEntryInfo(null, "/branch", 124))
            .thenReturn(new DirEntry("/", "branch", "author", new Date(), DirEntry.Kind.DIR, 123, 12345));

    when(serviceMock.list(null, "/branch/", 124))
            .thenReturn(new DirList(Collections.<DirEntry>emptyList(), new Properties()));

    when(serviceMock.getEntryInfo(null, "/trunk/file3.def", 123)).thenReturn(
            new DirEntry("/trunk", "file3.def", "author", new Date(), DirEntry.Kind.FILE, 123, 12345));

    final RepositoryName repositoryName = new RepositoryName("defaultsvn");
    final RevisionUpdate revisionUpdate = new RevisionUpdate(repositoryName, logEntries, false);

    final DirEntryCacheUpdater cacheUpdater = new DirEntryCacheUpdater(null, application);
    cacheUpdater.setRepositoryService(serviceMock);
    cacheUpdater.updateInternal(entryCache, null, revisionUpdate);

    Thread.sleep(500L); // TODO: Get rid of this!
    assertEquals(4, entryCache.getSize());
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.DeviationShedder.java

/**
 * Initialize this DeviationShedder./*from  www .  ja v a 2s.co m*/
 */
public DeviationShedder() {
    bundleTreeSetCache = new TreeSet<>();
    metricTreeSetCache = new TreeSet<>();
}