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:TextAreaDemo.java

public void insertUpdate(DocumentEvent ev) {
    if (ev.getLength() != 1) {
        return;/*from   w  w  w . ja  v  a 2  s .c om*/
    }

    int pos = ev.getOffset();
    String content = null;
    try {
        content = textArea.getText(0, pos + 1);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }

    // Find where the word starts
    int w;
    for (w = pos; w >= 0; w--) {
        if (!Character.isLetter(content.charAt(w))) {
            break;
        }
    }
    if (pos - w < 2) {
        // Too few chars
        return;
    }

    String prefix = content.substring(w + 1).toLowerCase();
    int n = Collections.binarySearch(words, prefix);
    if (n < 0 && -n <= words.size()) {
        String match = words.get(-n - 1);
        if (match.startsWith(prefix)) {
            // A completion is found
            String completion = match.substring(pos - w);
            // We cannot modify Document from within notification,
            // so we submit a task that does the change later
            SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
        }
    } else {
        // Nothing found
        mode = Mode.INSERT;
    }
}

From source file:edu.ku.brc.specify.utilapps.SetUpBuildDlg.java

public void createUI() {
    super.createUI();

    Specify.setUpSystemProperties();//from w  w  w  . j av  a  2 s.co  m
    UIFieldFormatterMgr.setDoingLocal(true);

    driverList = DatabaseDriverInfo.getDriversList();
    int inx = Collections.binarySearch(driverList,
            new DatabaseDriverInfo(dbDriverName, null, null, false, null));

    drivers = createComboBox(driverList);
    drivers.setSelectedIndex(inx);

    catNumFmtList = (Vector<UIFieldFormatterIFace>) UIFieldFormatterMgr.getInstance()
            .getFormatterList(CollectionObject.class, "catalogNumber");
    Collections.sort(catNumFmtList, new Comparator<UIFieldFormatterIFace>() {
        @Override
        public int compare(UIFieldFormatterIFace o1, UIFieldFormatterIFace o2) {
            return o1.getTitle().compareTo(o2.getTitle());
        }
    });
    for (UIFieldFormatterIFace fmt : catNumFmtList) {
        catNumFmtHash.put(fmt.getName(), fmt);
    }

    accNumFmtList = (Vector<UIFieldFormatterIFace>) UIFieldFormatterMgr.getInstance()
            .getFormatterList(Accession.class, "accessionNumber");
    Collections.sort(accNumFmtList, new Comparator<UIFieldFormatterIFace>() {
        @Override
        public int compare(UIFieldFormatterIFace o1, UIFieldFormatterIFace o2) {
            return o1.getTitle().compareTo(o2.getTitle());
        }
    });
    for (UIFieldFormatterIFace fmt : accNumFmtList) {
        accNumFmtHash.put(fmt.getName(), fmt);
    }

    catNumGrpList = new Vector<String>();
    catNumGrpList.add("None");
    catNumGrpList.add("Cat Global");
    catNumGrpList.add("Cat Test Group #1");
    catNumGrpList.add("Cat Test Group #2");
    for (DisciplineType d : DisciplineType.getDisciplineList()) {
        catNumGrpList.add("Cat " + d.getTitle() + " Group");
    }

    accNumGrpList = new Vector<String>();
    accNumGrpList.add("None");
    accNumGrpList.add("Acc Global");
    accNumGrpList.add("Acc Test Group #1");
    accNumGrpList.add("Acc Test Group #2");
    for (DisciplineType d : DisciplineType.getDisciplineList()) {
        accNumGrpList.add("Acc " + d.getTitle() + " Group");
    }

    databaseNameTxt = addAutoSelect(createTextField(databaseName, 15));
    dbUsernameTxtFld = addAutoSelect(createTextField(dbUser.first, 15));
    dbPasswdTxtFld = addAutoSelect(createPasswordField(dbUser.second, 15));

    saUsernameTxtFld = addAutoSelect(createTextField(saUser.first, 15));
    saPasswdTxtFld = addAutoSelect(createPasswordField(saUser.second, 15));

    usrUsernameTxtFld = addAutoSelect(createTextField(cmUser.first, 15));
    usrPasswdTxtFld = addAutoSelect(createPasswordField(cmUser.second, 15));

    extraCollectionsChk = createCheckBox("Create Extra Collections");
    extraCollectionsChk.setSelected(true);

    PanelBuilder builder = new PanelBuilder(new FormLayout("p,2px,p,10px,p,2px,p,10px,p,2px,p,p:g",
            UIHelper.createDuplicateJGoodiesDef("P", "2px", 9) + ",f:p:g,4px,p"));
    CellConstraints cc = new CellConstraints();
    int y = 1;
    builder.addSeparator("Username and Passwords", cc.xyw(1, y, 12));
    y += 2;
    builder.add(createLabel("IT Username:", SwingConstants.RIGHT), cc.xy(1, y));
    builder.add(dbUsernameTxtFld, cc.xy(3, y));
    builder.add(createLabel("Master Username:", SwingConstants.RIGHT), cc.xy(5, y));
    builder.add(saUsernameTxtFld, cc.xy(7, y));
    builder.add(createLabel("User Username:", SwingConstants.RIGHT), cc.xy(9, y));
    builder.add(usrUsernameTxtFld, cc.xy(11, y));
    y += 2;

    builder.add(createLabel("IT Password:", SwingConstants.RIGHT), cc.xy(1, y));
    builder.add(dbPasswdTxtFld, cc.xy(3, y));
    builder.add(createLabel("Master Password:", SwingConstants.RIGHT), cc.xy(5, y));
    builder.add(saPasswdTxtFld, cc.xy(7, y));
    builder.add(createLabel("User Password:", SwingConstants.RIGHT), cc.xy(9, y));
    builder.add(usrPasswdTxtFld, cc.xy(11, y));
    y += 2;

    builder.addSeparator("Database Info", cc.xyw(1, y, 12));
    y += 2;
    builder.add(createLabel("Database Name:", SwingConstants.RIGHT), cc.xy(1, y));
    builder.add(databaseNameTxt, cc.xy(3, y));
    y += 2;
    builder.add(createLabel("Driver:", SwingConstants.RIGHT), cc.xy(1, y));
    builder.add(drivers, cc.xy(3, y));
    y += 2;
    builder.addSeparator("Collection Options", cc.xyw(1, y, 12));
    y += 2;

    collChoiceList = loadPersistedChoices();

    fillChoicesWithDefaults();

    choiceTable = new JTable(new DisciplineSetupModel());
    choiceTable.setRowHeight((new JComboBox()).getPreferredSize().height);

    TableColumn col = choiceTable.getColumnModel().getColumn(2);
    col.setCellEditor(new MyComboBoxEditor(catNumFmtList, catNumFmtHash));
    col.setCellRenderer(new MyLabelRenderer(catNumFmtHash));

    col = choiceTable.getColumnModel().getColumn(3);
    col.setCellEditor(new MyComboBoxStringEditor(catNumGrpList));

    col = choiceTable.getColumnModel().getColumn(4);
    col.setCellEditor(new MyComboBoxEditor(accNumFmtList, accNumFmtHash));

    col = choiceTable.getColumnModel().getColumn(5);
    col.setCellEditor(new MyComboBoxStringEditor(accNumGrpList));
    //col.setCellRenderer(new MyComboBoxRenderer(catNumFmtList));

    UIHelper.makeTableHeadersCentered(choiceTable, false);
    calcColumnWidths(choiceTable);
    builder.add(UIHelper.createScrollPane(choiceTable), cc.xywh(1, y, 12, 1));
    y += 2;

    final JButton catGblBtn = createButton("Global Cat Nums");
    final JButton accGblBtn = createButton("Global Acc Nums");
    final JButton selectAllBtn = createButton("Select All");
    final JButton deSelectAll = createButton("Deselect All");
    final JButton defBtn = createButton("Revert");

    PanelBuilder btnBar = new PanelBuilder(
            new FormLayout("f:p:g," + UIHelper.createDuplicateJGoodiesDef("p", "4px", 5), "p"));
    btnBar.add(catGblBtn, cc.xy(2, 1));
    btnBar.add(accGblBtn, cc.xy(4, 1));
    btnBar.add(selectAllBtn, cc.xy(6, 1));
    btnBar.add(deSelectAll, cc.xy(8, 1));
    btnBar.add(defBtn, cc.xy(10, 1));
    builder.add(btnBar.getPanel(), cc.xywh(1, y, 12, 1));
    y += 2;

    catGblBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            setCatNumGroup("Cat Group");
        }
    });

    accGblBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            setAccNumGroup("Acc Group");
        }
    });

    selectAllBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            selectAll(true);
        }
    });

    deSelectAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            selectAll(false);
        }
    });

    cancelBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            closeDlg(true);
        }
    });

    okBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            saveChoices(collChoiceList);

            closeDlg(false);
        }
    });

    defBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            resetDefaults(collChoiceList);
        }
    });

    // make sure closing the window does the same thing as clicking cancel
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            cancelBtn.doClick();
        }
    });

    builder.setDefaultDialogBorder();

    contentPanel = builder.getPanel();
    mainPanel.add(contentPanel, BorderLayout.CENTER);

    pack();
    Dimension size = getSize();
    size.width = Math.max(size.width, 900);

    setSize(size);
}

From source file:com.widen.valet.importer.ImportZone.java

ZoneUpdateAction mergeAction(ZoneUpdateAction action, List<ZoneUpdateAction> existing) {
    int itemToMerge = Collections.binarySearch(existing, action);

    if (itemToMerge >= 0) {
        List<String> resources = existing.get(itemToMerge).resourceRecord;

        existing.remove(itemToMerge);/*from   w  ww.j  a  va2s  .c  om*/

        return ZoneUpdateAction.mergeResources(action, resources);
    } else {
        return action;
    }
}

From source file:org.pentaho.di.ui.i18n.MessagesSourceCrawler.java

/**
 * Add a key occurrence to the list of occurrences. The list is kept sorted on key and message package. If the key
 * already exists, we increment the number of occurrences.
 *
 * @param occ//from  w ww  .  j a va 2s  .c om
 *          The key occurrence to add
 */
public void addKeyOccurrence(KeyOccurrence occ) {

    // System.out.println("Adding key occurrence : folder="+occ.getSourceFolder()+", 
    // pkg="+occ.getMessagesPackage()+", key="+occ.getKey());

    String sourceFolder = occ.getSourceFolder();
    if (sourceFolder == null) {
        throw new RuntimeException(
                "No source folder found for key: " + occ.getKey() + " in package " + occ.getMessagesPackage());
    }
    String messagesPackage = occ.getMessagesPackage();

    // Do we have a map for the source folders?
    // If not, add one...
    //
    Map<String, List<KeyOccurrence>> packageOccurrences = sourcePackageOccurrences.get(sourceFolder);
    if (packageOccurrences == null) {
        packageOccurrences = new HashMap<String, List<KeyOccurrence>>();
        sourcePackageOccurrences.put(sourceFolder, packageOccurrences);
    }

    // Do we have a map entry for the occurrences list in the source folder?
    // If not, add a list for the messages package
    //
    List<KeyOccurrence> occurrences = packageOccurrences.get(messagesPackage);
    if (occurrences == null) {
        occurrences = new ArrayList<KeyOccurrence>();
        occurrences.add(occ);
        packageOccurrences.put(messagesPackage, occurrences);
    } else {
        int index = Collections.binarySearch(occurrences, occ);
        if (index < 0) {
            // Add it to the list, keep it sorted...
            //
            occurrences.add(-index - 1, occ);
        }
    }
}

From source file:org.opendatakit.common.android.utilities.NameUtil.java

/**
 * Determines whether or not the given name is valid for a user-defined
 * entity in the database. Valid names are determined to not begin with a
 * single underscore, not to begin with a digit, and to contain only unicode
 * appropriate word characters.//w ww .j a v a 2 s.  c o  m
 * @param name
 * @return true if valid else false
 */
public static boolean isValidUserDefinedDatabaseName(String name) {
    boolean matchHit = letterFirstPattern.matcher(name).matches();
    // TODO: uppercase is bad...
    boolean reserveHit = Collections.binarySearch(reservedNamesSortedList, name.toUpperCase(Locale.US)) >= 0;
    return (!reserveHit && matchHit);
}

From source file:org.apache.hadoop.hbase.regionserver.compactions.DateTieredCompactionPolicy.java

public boolean shouldPerformMajorCompaction(final Collection<StoreFile> filesToCompact) throws IOException {
    long mcTime = getNextMajorCompactTime(filesToCompact);
    if (filesToCompact == null || mcTime == 0) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("filesToCompact: " + filesToCompact + " mcTime: " + mcTime);
        }/*  ww w . j  a  va 2 s  . c om*/
        return false;
    }

    // TODO: Use better method for determining stamp of last major (HBASE-2990)
    long lowTimestamp = StoreUtils.getLowestTimestamp(filesToCompact);
    long now = EnvironmentEdgeManager.currentTime();
    if (lowTimestamp <= 0L || lowTimestamp >= (now - mcTime)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("lowTimestamp: " + lowTimestamp + " lowTimestamp: " + lowTimestamp + " now: " + now
                    + " mcTime: " + mcTime);
        }
        return false;
    }

    long cfTTL = this.storeConfigInfo.getStoreFileTtl();
    HDFSBlocksDistribution hdfsBlocksDistribution = new HDFSBlocksDistribution();
    List<Long> boundaries = getCompactBoundariesForMajor(filesToCompact, now);
    boolean[] filesInWindow = new boolean[boundaries.size()];

    for (StoreFile file : filesToCompact) {
        Long minTimestamp = file.getMinimumTimestamp();
        long oldest = (minTimestamp == null) ? Long.MIN_VALUE : now - minTimestamp.longValue();
        if (cfTTL != Long.MAX_VALUE && oldest >= cfTTL) {
            LOG.debug("Major compaction triggered on store " + this + "; for TTL maintenance");
            return true;
        }
        if (!file.isMajorCompaction() || file.isBulkLoadResult()) {
            LOG.debug("Major compaction triggered on store " + this
                    + ", because there are new files and time since last major compaction "
                    + (now - lowTimestamp) + "ms");
            return true;
        }

        int lowerWindowIndex = Collections.binarySearch(boundaries,
                minTimestamp == null ? (Long) Long.MAX_VALUE : minTimestamp);
        int upperWindowIndex = Collections.binarySearch(boundaries,
                file.getMaximumTimestamp() == null ? (Long) Long.MAX_VALUE : file.getMaximumTimestamp());
        if (lowerWindowIndex != upperWindowIndex) {
            LOG.debug("Major compaction triggered on store " + this + "; because file " + file.getPath()
                    + " has data with timestamps cross window boundaries");
            return true;
        } else if (filesInWindow[upperWindowIndex]) {
            LOG.debug("Major compaction triggered on store " + this
                    + "; because there are more than one file in some windows");
            return true;
        } else {
            filesInWindow[upperWindowIndex] = true;
        }
        hdfsBlocksDistribution.add(file.getHDFSBlockDistribution());
    }

    float blockLocalityIndex = hdfsBlocksDistribution
            .getBlockLocalityIndex(RSRpcServices.getHostname(comConf.conf, false));
    if (blockLocalityIndex < comConf.getMinLocalityToForceCompact()) {
        LOG.debug("Major compaction triggered on store " + this
                + "; to make hdfs blocks local, current blockLocalityIndex is " + blockLocalityIndex + " (min "
                + comConf.getMinLocalityToForceCompact() + ")");
        return true;
    }

    LOG.debug("Skipping major compaction of " + this + ", because the files are already major compacted");
    return false;
}

From source file:edu.ku.brc.af.core.NavBox.java

/**
 * Adds a NavBoxItemIFace item to the box insorted order.
 * @param item the NavBoxItemIFace item to be added
 * @param notify whether to have it relayout or not (true -> does layout)
 * @return the UI component for this item
 *//*from  ww w.  j a  v a  2s. co m*/
public Component insertSorted(final NavBoxItemIFace item) {
    int insertionInx = Math.abs(Collections.binarySearch(items, item)) - 1;
    return insert(item, true, true, insertionInx);
}

From source file:org.apache.hadoop.hbase.master.cleaner.ReplicationMetaCleaner.java

@Override
protected void chore() {
    try {/*from www .ja  v a 2  s .c  om*/
        Map<String, HTableDescriptor> tables = master.getTableDescriptors().getAllDescriptors();
        Map<String, Set<String>> serialTables = new HashMap<>();
        for (Map.Entry<String, HTableDescriptor> entry : tables.entrySet()) {
            boolean hasSerialScope = false;
            for (HColumnDescriptor column : entry.getValue().getFamilies()) {
                if (column.getScope() == HConstants.REPLICATION_SCOPE_SERIAL) {
                    hasSerialScope = true;
                    break;
                }
            }
            if (hasSerialScope) {
                serialTables.put(entry.getValue().getTableName().getNameAsString(), new HashSet<String>());
            }
        }
        if (serialTables.isEmpty()) {
            return;
        }

        Map<String, ReplicationPeerConfig> peers = replicationAdmin.listPeerConfigs();
        for (Map.Entry<String, ReplicationPeerConfig> entry : peers.entrySet()) {
            for (Map.Entry<TableName, List<String>> map : entry.getValue().getTableCFsMap().entrySet()) {
                if (serialTables.containsKey(map.getKey().getNameAsString())) {
                    serialTables.get(map.getKey().getNameAsString()).add(entry.getKey());
                    break;
                }
            }
        }

        Map<String, List<Long>> barrierMap = MetaTableAccessor.getAllBarriers(master.getConnection());
        for (Map.Entry<String, List<Long>> entry : barrierMap.entrySet()) {
            String encodedName = entry.getKey();
            byte[] encodedBytes = Bytes.toBytes(encodedName);
            boolean canClearRegion = false;
            Map<String, Long> posMap = MetaTableAccessor
                    .getReplicationPositionForAllPeer(master.getConnection(), encodedBytes);
            if (posMap.isEmpty()) {
                continue;
            }

            String tableName = MetaTableAccessor.getSerialReplicationTableName(master.getConnection(),
                    encodedBytes);
            Set<String> confPeers = serialTables.get(tableName);
            if (confPeers == null) {
                // This table doesn't exist or all cf's scope is not serial any more, we can clear meta.
                canClearRegion = true;
            } else {
                if (!allPeersHavePosition(confPeers, posMap)) {
                    continue;
                }

                String daughterValue = MetaTableAccessor
                        .getSerialReplicationDaughterRegion(master.getConnection(), encodedBytes);
                if (daughterValue != null) {
                    //this region is merged or split
                    boolean allDaughterStart = true;
                    String[] daughterRegions = daughterValue.split(",");
                    for (String daughter : daughterRegions) {
                        byte[] region = Bytes.toBytes(daughter);
                        if (!MetaTableAccessor.getReplicationBarriers(master.getConnection(), region).isEmpty()
                                && !allPeersHavePosition(confPeers, MetaTableAccessor
                                        .getReplicationPositionForAllPeer(master.getConnection(), region))) {
                            allDaughterStart = false;
                            break;
                        }
                    }
                    if (allDaughterStart) {
                        canClearRegion = true;
                    }
                }
            }
            if (canClearRegion) {
                Delete delete = new Delete(encodedBytes);
                delete.addFamily(HConstants.REPLICATION_POSITION_FAMILY);
                delete.addFamily(HConstants.REPLICATION_BARRIER_FAMILY);
                try (Table metaTable = master.getConnection().getTable(TableName.META_TABLE_NAME)) {
                    metaTable.delete(delete);
                }
            } else {

                // Barriers whose seq is larger than min pos of all peers, and the last barrier whose seq
                // is smaller than min pos should be kept. All other barriers can be deleted.

                long minPos = Long.MAX_VALUE;
                for (Map.Entry<String, Long> pos : posMap.entrySet()) {
                    minPos = Math.min(minPos, pos.getValue());
                }
                List<Long> barriers = entry.getValue();
                int index = Collections.binarySearch(barriers, minPos);
                if (index < 0) {
                    index = -index - 1;
                }
                Delete delete = new Delete(encodedBytes);
                for (int i = 0; i < index - 1; i++) {
                    delete.addColumn(HConstants.REPLICATION_BARRIER_FAMILY, Bytes.toBytes(barriers.get(i)));
                }
                try (Table metaTable = master.getConnection().getTable(TableName.META_TABLE_NAME)) {
                    metaTable.delete(delete);
                }
            }

        }

    } catch (IOException e) {
        LOG.error("Exception during cleaning up.", e);
    }

}

From source file:org.apache.hadoop.fs.TestFileStatus.java

@Test
public void testCompareTo() throws IOException {
    Path path1 = new Path("path1");
    Path path2 = new Path("path2");
    FileStatus fileStatus1 = new FileStatus(1, true, 1, 1, 1, 1, FsPermission.valueOf("-rw-rw-rw-"), "one",
            "one", null, path1);
    FileStatus fileStatus2 = new FileStatus(1, true, 1, 1, 1, 1, FsPermission.valueOf("-rw-rw-rw-"), "one",
            "one", null, path2);
    assertTrue(fileStatus1.compareTo(fileStatus2) < 0);
    assertTrue(fileStatus2.compareTo(fileStatus1) > 0);

    List<FileStatus> statList = new ArrayList<>();
    statList.add(fileStatus1);//from  ww  w. j a va  2  s .c  o  m
    statList.add(fileStatus2);
    assertTrue(Collections.binarySearch(statList, fileStatus1) > -1);
}

From source file:org.jaffa.qm.util.PropertyFilter.java

/** Returns true if the field is included based on the rules.
 * @param field the field//from w w w .  jav  a  2s  . c  o  m
 * @return true if the field is included based on the rules.
 */
public boolean isFieldIncluded(String field) {
    return m_filteredFields != null && Collections.binarySearch(m_filteredFields, field) >= 0;
}