Example usage for java.util Collections binarySearch

List of usage examples for java.util Collections binarySearch

Introduction

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

Prototype

public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) 

Source Link

Document

Searches the specified list for the specified object using the binary search algorithm.

Usage

From source file:org.apache.juddi.mapping.MappingModelToApi.java

public static void mapAssertionStatusItem(org.apache.juddi.model.PublisherAssertion modelPublisherAssertion,
        org.uddi.api_v3.AssertionStatusItem apiAssertionStatusItem, List<?> businessKeys)
        throws DispositionReportFaultMessage {

    apiAssertionStatusItem.setFromKey(modelPublisherAssertion.getId().getFromKey());
    apiAssertionStatusItem.setToKey(modelPublisherAssertion.getId().getToKey());

    org.uddi.api_v3.KeyedReference keyedRef = new org.uddi.api_v3.KeyedReference();
    keyedRef.setTModelKey(modelPublisherAssertion.getTmodelKey());
    keyedRef.setKeyName(modelPublisherAssertion.getKeyName());
    keyedRef.setKeyValue(modelPublisherAssertion.getKeyValue());

    apiAssertionStatusItem.setKeyedReference(keyedRef);

    if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck())
            && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck()))
        apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_COMPLETE);
    else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck())
            && "true".equalsIgnoreCase(modelPublisherAssertion.getToCheck()))
        apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_FROM_KEY_INCOMPLETE);
    else if ("true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck())
            && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck()))
        apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_TO_KEY_INCOMPLETE);
    else if (!"true".equalsIgnoreCase(modelPublisherAssertion.getFromCheck())
            && !"true".equalsIgnoreCase(modelPublisherAssertion.getToCheck()))
        apiAssertionStatusItem.setCompletionStatus(CompletionStatus.STATUS_BOTH_INCOMPLETE);

    org.uddi.api_v3.KeysOwned keysOwned = new org.uddi.api_v3.KeysOwned();

    //converting resultList to simple List
    List<String> businessKeyList = new ArrayList<String>();
    for (Object businessKey : businessKeys) {
        businessKeyList.add(String.valueOf(businessKey));
    }//from   ww w  .j  a  va  2 s.  co  m
    Collections.sort(businessKeyList);
    if (Collections.binarySearch(businessKeyList,
            modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey()) >= 0)
        keysOwned.setFromKey(modelPublisherAssertion.getBusinessEntityByFromKey().getEntityKey());

    if (Collections.binarySearch(businessKeyList,
            modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey()) >= 0)
        keysOwned.setToKey(modelPublisherAssertion.getBusinessEntityByToKey().getEntityKey());
    if (keysOwned.getFromKey() == null && keysOwned.getToKey() == null) {
        throw new FatalErrorException(new ErrorMessage("errors.invalidKey.KeysOwned"));
    }
    apiAssertionStatusItem.setKeysOwned(keysOwned);
}

From source file:org.briljantframework.array.Arrays.java

/**
 * Searches the specified array for the specified object using the binary search algorithm. The
 * array must be sorted into ascending order
 *
 * @param array the array/*w w  w.j av  a 2  s.  c o  m*/
 * @param x the element
 * @return the index of the search key, if it is contained in the list; otherwise,
 *         <tt>(-(<i>insertion point</i>) - 1)</tt>.
 * @see Collections#binarySearch(List, Object)
 */
public static <T> int binarySearch(Array<? extends Comparable<? super T>> array, T x) {
    return Collections.binarySearch(array.toList(), x);
}

From source file:org.briljantframework.array.Arrays.java

/**
 * Locate the insertion point for value in a to maintain sorted order. If value is already present
 * in the array, the insertion point will be before (to the left of) any existing entries. The
 * array must be sorted in ascending order.
 *
 * @param array the array//from  w w w .  j a va2s.  c  o m
 * @param value the value
 * @param <T> the class of objects in the array
 * @return the insertion point of the value
 */
public static <T> int bisectLeft(Array<? extends Comparable<? super T>> array, T value) {
    int i = Collections.binarySearch(array.toList(), value);
    if (i < 0) {
        return -i - 1;
    } else {
        return i;
    }
}

From source file:org.briljantframework.array.Arrays.java

/**
 * Locate the insertion point for value in a to maintain sorted order. If value is already present
 * in the array, the insertion point will be after (to the right of) any existing entries. The
 * array must be sorted in ascending order.
 *
 * @param array the array//from ww w .  j  ava2s  .com
 * @param value the value
 * @param <T> the class of objects in the array
 * @return the insertion point of the value
 * @see #bisectLeft(Array, Object)
 */
public static <T> int bisectRight(Array<? extends Comparable<? super T>> array, T value) {
    int i = Collections.binarySearch(array.toList(), value);
    if (i < 0) {
        return -i - 1;
    } else {
        return i + 1;
    }
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void doBlastn(final String fasta, final String evaluestr, final boolean ids, final RunnableResult rr,
        boolean show) {
    /*File blastn;/*from  w  ww .  jav  a2s. co  m*/
    File blastp;
    File makeblastdb;
    File blastx = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastx.exe" );
    if( !blastx.exists() ) {
       blastx = new File( "/opt/ncbi-blast-2.2.29+/bin/blastx" );
       if( !blastx.exists() ) {
    blastx = new File( "/usr/local/ncbi/blast/bin/blastx" );
    blastn = new File( "/usr/local/ncbi/blast/bin/blastn" );
    blastp = new File( "/usr/local/ncbi/blast/bin/blastp" );
            
    makeblastdb = new File( "/usr/local/ncbi/blast/bin/makeblastdb" );
       } else {
    blastn = new File( "/opt/ncbi-blast-2.2.29+/bin/blastn" );
    blastp = new File( "/opt/ncbi-blast-2.2.29+/bin/blastp" );
            
    makeblastdb = new File( "/opt/ncbi-blast-2.2.29+/bin/makeblastdb" );
       }
    } else {
       blastn = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastn.exe" );
       blastp = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastp.exe" );
               
       makeblastdb = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\makeblastdb.exe" );
    }*/

    int procs = Runtime.getRuntime().availableProcessors();
    String[] mcmds = { "makeblastdb", "-dbtype", "nucl", "-title", "tmp", "-out", "tmp" };
    List<String> lcmd = new ArrayList<String>(Arrays.asList(mcmds));

    final ProcessBuilder mpb = new ProcessBuilder(lcmd);
    mpb.redirectErrorStream(true);
    try {
        final Process mp = mpb.start();

        new Thread() {
            public void run() {
                try {
                    OutputStream pos = mp.getOutputStream();
                    for (String cname : geneset.contigmap.keySet()) {
                        Sequence c = geneset.contigmap.get(cname);
                        if (ids)
                            pos.write((">" + c.id + "\n").getBytes());
                        else {
                            pos.write((">" + c.getName() + "\n").getBytes());
                        }
                        StringBuilder sb = c.getStringBuilder();
                        for (int i = 0; i < sb.length(); i += 70) {
                            pos.write(sb.substring(i, Math.min(sb.length(), i + 70)).getBytes());
                        }
                        pos.write('\n');
                    }
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run() {
                try {
                    InputStream pin = mp.getInputStream();
                    InputStreamReader rdr = new InputStreamReader(pin);
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = br.readLine();
                    }
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.run();

        //File blastFile = blastn; //dbType.equals("prot") ? type.equals("prot") ? blastp : blastx : blastn;

        String[] cmds1 = { "blastn", "-dust", "no", "-perc_identity", "99", "-word_size", "21", "-query", "-",
                "-db", "tmp", "-evalue", evaluestr, "-num_threads", Integer.toString(procs) };
        String[] cmds2 = { "blastn", "-query", "-", "-db", "tmp", "-evalue", evaluestr, "-num_threads",
                Integer.toString(procs) };
        String[] cmds = show ? cmds2 : cmds1;

        lcmd = new ArrayList<String>(Arrays.asList(cmds));
        //String[] exts = extrapar.trim().split("[\t ]+");

        ProcessBuilder pb = new ProcessBuilder(lcmd);
        pb.redirectErrorStream(true);
        final Process p = pb.start();

        final Thread t = new Thread() {
            public void run() {
                try {
                    OutputStream pos = p.getOutputStream();
                    pos.write(fasta.getBytes());
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        Map<String, Set<String>> tph = new HashMap<String, Set<String>>();
        Map<String, Map<String, String>> tvp = new HashMap<String, Map<String, String>>();
        Map<String, Map<String, String>> tmr = new HashMap<String, Map<String, String>>();

        Map<String, Integer> specindex = new LinkedHashMap<String, Integer>();
        Map<String, Integer> phindex = new LinkedHashMap<String, Integer>();

        /*final Thread t2 = new Thread() {
           public void run() {*/
        try {
            System.err.println("WHY NOT");
            InputStreamReader rdr = new InputStreamReader(p.getInputStream());
            //FileReader fr = new FileReader( new File("c:/dot.blastout") );

            String qspec = null;
            String query = null;
            String ctype = null;
            Annotation at = new Annotation();
            int o = 0;
            StringBuilder res = new StringBuilder();
            BufferedReader br = new BufferedReader(rdr);
            String line = br.readLine();
            res.append(line + "\n");
            while (line != null) {
                if (line.startsWith("Query= ")) {
                    query = line.substring(7, line.length());
                    int e = query.indexOf("CRISPR") - 1;
                    if (e > 0) {
                        qspec = query.substring(0, e);
                        qspec = Sequence.getSpec(qspec);
                        String rest = query.substring(e + 8);
                        int ri = rest.lastIndexOf('-');
                        if (ri != -1)
                            ctype = rest.substring(ri + 1);
                    } else {
                        System.err.println();
                    }

                    line = br.readLine();
                    res.append(line + "\n");
                    while (!line.startsWith("Length")) {
                        line = br.readLine();
                        res.append(line + "\n");
                    }
                    o = Integer.parseInt(line.substring(7));
                } else if (line.startsWith("> ")) {
                    String contname = line.substring(1).trim();
                    //line = br.readLine();
                    //res.append( line+"\n" );
                    //int o = Integer.parseInt( line.substring(7) );

                    Sequence cont = geneset.contigmap.get(contname);

                    if (cont != null) {
                        int start = -1;
                        int stop = 0;
                        line = br.readLine();
                        res.append(line + "\n");
                        String lastmatch = null;
                        while (line != null && !line.startsWith(">")
                                && !line.startsWith("Query=") /*&& !line.contains("Expect =")*/ ) {
                            if (line.startsWith("Sbjct")) {
                                String[] split = line.split("[\t ]+");
                                int k = Integer.parseInt(split[1]);
                                int m = Integer.parseInt(split[3]);
                                lastmatch = split[2];

                                if (start == -1)
                                    start = k;
                                stop = m;
                            }
                            line = br.readLine();
                            res.append(line + "\n");
                        }

                        if (start > stop) {
                            int tmp = start;
                            start = stop;
                            stop = tmp;
                        }

                        at.start = start;
                        at.stop = stop;

                        //if( stop - start < o*2 ) {
                        List<Annotation> lann = cont.getAnnotations();
                        if (lann != null) {
                            int k = Collections.binarySearch(lann, at);

                            //System.err.println( "kkk  " + k + "   " + lann.size() );

                            if (k < 0)
                                k = -(k + 1) - 1;

                            Annotation ann = lann.get(Math.max(0, k));

                            boolean yes = true;
                            if (ann.type != null && ann.type.contains("ummer")) {
                                yes = false;
                            }

                            int u = k - 1;
                            Annotation nann = null;
                            if (u >= 0 && u < lann.size())
                                nann = lann.get(u);

                            u = k + 1;
                            Annotation rann = null;
                            if (u >= 0 && u < lann.size())
                                rann = lann.get(u);

                            if (nann != null && nann.type != null && nann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (rann != null && rann.type != null && rann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (!yes) {
                                //System.err.println();
                            }

                            Gene g = ann.getGene();
                            String desig = ann.designation;

                            if (yes && g != null) { //ann.stop > at.start && ann.start < at.stop ) {
                                GeneGroup gg = g.getGeneGroup();
                                if (desig != null && desig.contains("phage")) {
                                    if (!phindex.containsKey(desig))
                                        phindex.put(desig, phindex.size());

                                    Map<String, String> tvps;
                                    String specname = qspec;//Sequence.nameFix(qspec, true);
                                    if (!specindex.containsKey(specname))
                                        specindex.put(specname, specindex.size());

                                    if (tvp.containsKey(specname)) {
                                        tvps = tvp.get(specname);
                                    } else {
                                        tvps = new HashMap<String, String>();
                                        tvp.put(specname, tvps);
                                    }
                                    tvps.put(desig, ctype);

                                    String contspec = cont.getSpec();
                                    System.err.println(query + " asdf " + contspec + " " + lastmatch + "  "
                                            + at.start + " " + at.stop + "  " + ann.start + " " + ann.stop
                                            + " rann " + (rann != null ? rann.start + "  " + rann.stop : "")
                                            + " nann " + (nann != null ? nann.start + "  " + nann.stop : ""));
                                    if (qspec.equals(contspec)) {
                                        if (tmr.containsKey(specname)) {
                                            tvps = tmr.get(specname);
                                        } else {
                                            tvps = new HashMap<String, String>();
                                            tmr.put(specname, tvps);
                                        }
                                        tvps.put(desig, ctype);
                                    }

                                    /*if( specname.contains("brockianus_MAT_338") ) {
                                       System.err.println();
                                    }*/
                                }

                                Platform.runLater(() -> {
                                    if (!isGeneview()) {
                                        /*int ggindex = geneset.allgenegroups.indexOf( gg );
                                        int i = table.convertRowIndexToView( ggindex );
                                        if( i != -1 ) table.addRowSelectionInterval(i, i);*/

                                        table.getSelectionModel().select(gg);
                                    } else {
                                        /*int gindex = geneset.genelist.indexOf( g );
                                        int i = table.convertRowIndexToView( gindex );
                                        table.addRowSelectionInterval(i, i);*/

                                        gtable.getSelectionModel().select(g);
                                    }
                                });
                            }

                            /*for( Annotation ann : lann ) {
                               if( ann.stop > start && ann.start < stop ) {
                            Gene g = ann.getGene();
                            if( g != null ) {
                               if( table.getModel() == groupModel ) {
                                  GeneGroup gg = g.getGeneGroup();
                                          
                                  int ggindex = allgenegroups.indexOf( gg );
                                  int i = table.convertRowIndexToView( ggindex );
                                  table.addRowSelectionInterval(i, i);
                               } else if( table.getModel() == defaultModel ) {
                                  int gindex = geneset.genelist.indexOf( g );
                                  int i = table.convertRowIndexToView( gindex );
                                  table.addRowSelectionInterval(i, i);
                               }
                            }
                               }
                            }*/
                        }
                        //}
                        continue;
                    }
                }

                /*int i = line.indexOf(' ', 2);
                if( i == -1 ) i = line.length();
                String id = line.substring(2, i);
                        
                Gene g = genemap.get( id );
                if( g != null ) {
                   if( table.getModel() == groupModel ) {
                      i = allgenegroups.indexOf( g.getGeneGroup() );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   } else {
                      i = geneset.genelist.indexOf( g );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   }
                }
                        
                String stuff = line+"\n";
                line = br.readLine();
                while( line != null && !line.startsWith("Query=") && !line.startsWith("> ") ) {
                   stuff += line+"\n";
                   line = br.readLine();
                }
                if( rr != null ) {
                   rr.run( stuff );
                   //res += line+"\n";
                }
                } //else*/
                line = br.readLine();
                res.append(line + "\n");
            }
            br.close();
            p.destroy();

            for (String specname : geneset.speccontigMap.keySet()) {
                List<Sequence> lseq = geneset.speccontigMap.get(specname);
                for (Sequence seq : lseq) {
                    List<Annotation> lann = seq.getAnnotations();
                    if (lann != null) {
                        for (Annotation a : lann) {
                            String desig = a.designation;
                            if (desig != null && desig.contains("phage") && phindex.containsKey(desig)) {
                                if (!specindex.containsKey(specname))
                                    specindex.put(specname, specindex.size());

                                Set<String> tvps;
                                if (tph.containsKey(specname)) {
                                    tvps = tph.get(specname);
                                } else {
                                    tvps = new HashSet<String>();
                                    tph.put(specname, tvps);
                                }
                                tvps.add(desig);
                            }
                        }
                    }
                }
            }

            int k = 0;
            int u = 0;
            Workbook wb = new XSSFWorkbook();
            Sheet sh = wb.createSheet("Phage");
            Row rw = sh.createRow(u++);
            //res = new StringBuilder();
            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
                rw.createCell(++k).setCellValue(ph);
            }
            res.append("\n");
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);
                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else {
                            res.append("\t");
                        }

                        k++;
                    }
                }
                res.append("\n");
            }

            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
            }
            res.append("\n");

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tmr.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Set<String> set = tph.get(rspec);
                Map<String, String> setvp = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.contains(ph)) {
                            if (setvp != null && setvp.containsKey(ph)) {
                                res.append("\tyes wspacer");
                                rw.createCell(k).setCellValue("yes wspacer");
                            } else {
                                res.append("\tyes");
                                rw.createCell(k).setCellValue("yes");
                            }
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            File file = new File("/Users/sigmar/phage.xlsx");
            FileOutputStream fos = new FileOutputStream(file);
            wb.write(fos);
            fos.close();

            Desktop.getDesktop().open(file);

            //if( !show ) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(800, 600);

            JTextArea ta = new JTextArea();
            ta.setFont(new Font("monospaced", Font.PLAIN, 12));
            ta.append(res.toString());
            JScrollPane sp = new JScrollPane(ta);
            frame.add(sp);

            frame.setVisible(true);

            FileWriter fw = new FileWriter("/Users/sigmar/file.txt");
            fw.write(res.toString());
            fw.close();

            if (rr != null)
                rr.run("close");
            //}

            /*if( rr != null ) {
             rr.run( res );
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*   }
        };
        t2.start();*/
        //fr.close();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

From source file:com.rfo.basic.Run.java

public static int newVarIndex(ArrayList<String> names, String name) {
    int index = Collections.binarySearch(names, name);
    if (index >= 0) {
        throw new InvalidParameterException("newVarIndex: variable " + name + " already exists");
    }//from ww w  . ja  va 2 s .  c om
    return -(index + 1); // return the absolute index
    //      Alternate ending to add log:
    //      index = -(index + 1);                        // make the index absolute
    //      Log.v(LOGTAG, CLASSTAG + " newVarIndex() create var " + name + " at index " + index + "/" + vNames.size() + "(start=" + vStart + ")");
    //      return index;
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void initSearchBar() {
    if (searchBarInitialized)
        return;/*from w w  w .ja  v  a2s. c om*/
    final EditText field = (EditText) searchBarView.findViewById(R.id.board_search_field);
    final TextView results = (TextView) searchBarView.findViewById(R.id.board_search_result);
    if (pageType == TYPE_POSTSLIST) {
        field.setHint(R.string.search_bar_in_thread_hint);
    }
    final View.OnClickListener searchOnClickListener = new View.OnClickListener() {
        private int lastFound = -1;

        @Override
        public void onClick(View v) {
            if (v != null && v.getId() == R.id.board_search_close) {
                searchHighlightActive = false;
                adapter.notifyDataSetChanged();
                searchBarView.setVisibility(View.GONE);
            } else if (listView != null && listView.getChildCount() > 0 && adapter != null
                    && cachedSearchResults != null) {
                boolean atEnd = listView.getChildAt(listView.getChildCount() - 1).getTop()
                        + listView.getChildAt(listView.getChildCount() - 1).getHeight() == listView.getHeight();

                View topView = listView.getChildAt(0);
                if ((v == null || v.getId() == R.id.board_search_previous) && topView.getTop() < 0
                        && listView.getChildCount() > 1)
                    topView = listView.getChildAt(1);
                int currentListPosition = listView.getPositionForView(topView);

                int newResultIndex = Collections.binarySearch(cachedSearchResults, currentListPosition);
                if (newResultIndex >= 0) {
                    if (v != null) {
                        if (v.getId() == R.id.board_search_next)
                            ++newResultIndex;
                        else if (v.getId() == R.id.board_search_previous)
                            --newResultIndex;
                    }
                } else {
                    newResultIndex = -newResultIndex - 1;
                    if (v != null && v.getId() == R.id.board_search_previous)
                        --newResultIndex;
                }
                while (newResultIndex < 0)
                    newResultIndex += cachedSearchResults.size();
                newResultIndex %= cachedSearchResults.size();

                if (v != null && v.getId() == R.id.board_search_next && lastFound == newResultIndex && atEnd)
                    newResultIndex = 0;
                lastFound = newResultIndex;

                listView.setSelection(cachedSearchResults.get(newResultIndex));
                results.setText((newResultIndex + 1) + "/" + cachedSearchResults.size());
            }
        }
    };
    for (int id : new int[] { R.id.board_search_close, R.id.board_search_previous, R.id.board_search_next }) {
        searchBarView.findViewById(id).setOnClickListener(searchOnClickListener);
    }
    field.setOnKeyListener(new View.OnKeyListener() {
        private boolean searchUsingChan() {
            if (pageType != TYPE_THREADSLIST)
                return false;
            if (presentationModel != null)
                if (presentationModel.source != null)
                    if (presentationModel.source.boardModel != null)
                        if (!presentationModel.source.boardModel.searchAllowed)
                            return false;
            return true;
        }

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (searchUsingChan()) {
                    UrlPageModel model = new UrlPageModel();
                    model.chanName = chan.getChanName();
                    model.type = UrlPageModel.TYPE_SEARCHPAGE;
                    model.boardName = tabModel.pageModel.boardName;
                    model.searchRequest = field.getText().toString();
                    UrlHandler.open(model, activity);
                } else {
                    int highlightColor = ThemeUtils.getThemeColor(activity.getTheme(),
                            R.attr.searchHighlightBackground, Color.RED);
                    String request = field.getText().toString().toLowerCase(Locale.US);

                    if (cachedSearchRequest == null || !request.equals(cachedSearchRequest)) {
                        cachedSearchRequest = request;
                        cachedSearchResults = new ArrayList<Integer>();
                        cachedSearchHighlightedSpanables = new SparseArray<Spanned>();
                        List<PresentationItemModel> safePresentationList = presentationModel
                                .getSafePresentationList();
                        if (safePresentationList != null) {
                            for (int i = 0; i < safePresentationList.size(); ++i) {
                                PresentationItemModel model = safePresentationList.get(i);
                                if (model.hidden && !staticSettings.showHiddenItems)
                                    continue;
                                String comment = model.spannedComment.toString().toLowerCase(Locale.US)
                                        .replace('\n', ' ');
                                List<Integer> altFoundPositions = null;
                                if (model.floating) {
                                    int floatingpos = FlowTextHelper.getFloatingPosition(model.spannedComment);
                                    if (floatingpos != -1 && floatingpos < model.spannedComment.length()
                                            && model.spannedComment.charAt(floatingpos) == '\n') {
                                        String altcomment = comment.substring(0, floatingpos)
                                                + comment.substring(floatingpos + 1,
                                                        Math.min(model.spannedComment.length(),
                                                                floatingpos + request.length()));
                                        int start = 0;
                                        int curpos;
                                        while (start < altcomment.length()
                                                && (curpos = altcomment.indexOf(request, start)) != -1) {
                                            if (altFoundPositions == null)
                                                altFoundPositions = new ArrayList<Integer>();
                                            altFoundPositions.add(curpos);
                                            start = curpos + request.length();
                                        }
                                    }
                                }

                                if (comment.contains(request) || altFoundPositions != null) {
                                    cachedSearchResults.add(Integer.valueOf(i));
                                    SpannableStringBuilder spannedHighlited = new SpannableStringBuilder(
                                            safePresentationList.get(i).spannedComment);
                                    int start = 0;
                                    int curpos;
                                    while (start < comment.length()
                                            && (curpos = comment.indexOf(request, start)) != -1) {
                                        start = curpos + request.length();
                                        if (altFoundPositions != null
                                                && Collections.binarySearch(altFoundPositions, curpos) >= 0)
                                            continue;
                                        spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                curpos, curpos + request.length(),
                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    }
                                    if (altFoundPositions != null) {
                                        for (Integer pos : altFoundPositions) {
                                            spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                    pos, pos + request.length(),
                                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }
                                    }
                                    cachedSearchHighlightedSpanables.put(i, spannedHighlited);
                                }
                            }
                        }
                    }

                    if (cachedSearchResults.size() == 0) {
                        Toast.makeText(activity, R.string.notification_not_found, Toast.LENGTH_LONG).show();
                    } else {
                        boolean firstTime = !searchHighlightActive;
                        searchHighlightActive = true;
                        adapter.notifyDataSetChanged();
                        searchBarView.findViewById(R.id.board_search_next).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_previous).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_result).setVisibility(View.VISIBLE);
                        searchOnClickListener
                                .onClick(firstTime ? null : searchBarView.findViewById(R.id.board_search_next));
                    }
                }
                try {
                    InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(field.getWindowToken(), 0);
                } catch (Exception e) {
                    Logger.e(TAG, e);
                }
                return true;
            }
            return false;
        }
    });
    field.addTextChangedListener(new OnSearchTextChangedListener(this));
    field.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    if (resources.getDimensionPixelSize(R.dimen.panel_height) < field.getMeasuredHeight())
        searchBarView.getLayoutParams().height = field.getMeasuredHeight();
    searchBarInitialized = true;
}