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:com.golemgame.properties.fengGUI.KnottedFunctionPane.java

private Knot findKnot(float x, float y, float fX, float fY) {
    if (!knots.isEmpty()) {
        comparator.getTranslation().setLocation(fX, fY);
        int pos = Collections.binarySearch(knots, comparator);
        //find the closest knot, and then check if it contacts this position;
        if (pos < 0) {
            pos = -pos;//  w w w.j  a  va  2  s  . co  m
        }
        if (pos >= knots.size())
            pos = knots.size() - 1;

        Knot pressed = knots.get(pos);

        if (pressed.testContact(x, y)) {//if a prexisting knot was clicked.
            return pressed;

        }

        if (selected == null && pos > 0) {
            pressed = knots.get(pos - 1);
            if (pressed.testContact(x, y)) {
                return pressed;

            }
        }
        if (selected == null && pos > 1) {
            pressed = knots.get(pos - 2);
            if (pressed.testContact(x, y)) {
                return pressed;

            }

        }
        if (selected == null && pos < knots.size() - 2) {
            pressed = knots.get(pos + 1);
            if (pressed.testContact(x, y)) {
                return pressed;

            }
        }
    }
    return null;
}

From source file:edu.ku.brc.specify.conversion.CustomDBConverterPanel.java

/**
 * Creates the UI for the login and hooks up any listeners.
 * @param isDlg  whether the parent is a dialog (false mean JFrame)
 *//*  w  w  w  . j a  v a  2 s . c o m*/
protected void createUI(final boolean isDlg) {
    PropertiesPickListAdapter dbPickList = new PropertiesPickListAdapter("convert.databasesSource");
    PropertiesPickListAdapter svPickList = new PropertiesPickListAdapter("convert.serversSource");

    PropertiesPickListAdapter dbDestPickList = new PropertiesPickListAdapter("convert.databasesDest");
    PropertiesPickListAdapter svDestPickList = new PropertiesPickListAdapter("convert.serversDest");

    usernameSource = createTextField(20);
    passwordSource = createPasswordField(20);

    usernameDest = createTextField(20);
    passwordDest = createPasswordField(20);

    databasesSource = new ValComboBox(dbPickList);
    serversSource = new ValComboBox(svPickList);

    databasesDest = new ValComboBox(dbDestPickList);
    serversDest = new ValComboBox(svDestPickList);

    setControlSize(passwordSource);
    setControlSize(passwordDest);
    setControlSize(databasesSource);
    setControlSize(serversSource);
    setControlSize(databasesDest);
    setControlSize(serversDest);

    dbPickList.setComboBox(databasesSource);
    svPickList.setComboBox(serversSource);

    dbDestPickList.setComboBox(databasesDest);
    svDestPickList.setComboBox(serversDest);

    // autoLoginSourceCBX = createCheckBox(getResourceString("autologin"));
    rememberUsernameSourceCBX = createCheckBox(getResourceString("rememberuser"));
    rememberPasswordSourceCBX = createCheckBox(getResourceString("rememberpassword"));

    autoLoginDestCBX = createCheckBox(getResourceString("autologin"));
    rememberUsernameDestCBX = createCheckBox(getResourceString("rememberuser"));
    rememberPasswordDestCBX = createCheckBox(getResourceString("rememberpassword"));

    statusBar = new JStatusBar();
    statusBar.setErrorIcon(IconManager.getIcon("Error", IconManager.IconSize.Std16));

    cancelBtn = createButton(getResourceString("CANCEL"));
    loginBtn = createButton(getResourceString("Login"));
    helpBtn = createButton(getResourceString("HELP"));

    forwardImgIcon = IconManager.getIcon("Forward");
    downImgIcon = IconManager.getIcon("Down");
    //moreBtn = createCheckBox("More", forwardImgIcon); // XXX I18N

    // Extra
    dbDrivers = DatabaseDriverInfo.getDriversList();
    dbDriverCBX = createComboBox(dbDrivers);
    dbDriverCBX2 = createComboBox(dbDrivers);

    if (dbDrivers.size() > 0) {
        String selectedStr = AppPreferences.getLocalPrefs().get("convert.dbdriverSource_selected", "SQLServer");
        int inx = Collections.binarySearch(dbDrivers,
                new DatabaseDriverInfo(selectedStr, null, null, false, null));
        dbDriverCBX.setSelectedIndex(inx > -1 ? inx : -1);
        selectedStr = AppPreferences.getLocalPrefs().get("convert.dbdriverDest_selected", "SQLServer");
        inx = Collections.binarySearch(dbDrivers, new DatabaseDriverInfo(selectedStr, null, null, false, null));
        dbDriverCBX2.setSelectedIndex(inx > -1 ? inx : -1);

    } else {
        JOptionPane.showConfirmDialog(null, getResourceString("NO_DBDRIVERS"),
                getResourceString("NO_DBDRIVERS_TITLE"), JOptionPane.CLOSED_OPTION);
        System.exit(1);
    }

    dbDriverCBX.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            updateUIControls();
        }
    });

    dbDriverCBX2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            updateUIControls();
        }
    });
    addFocusListenerForTextComp(usernameSource);
    addFocusListenerForTextComp(passwordSource);

    addKeyListenerFor(usernameSource, !isDlg);
    addKeyListenerFor(passwordSource, !isDlg);

    addKeyListenerFor(databasesSource.getTextField(), !isDlg);
    addKeyListenerFor(serversSource.getTextField(), !isDlg);

    addFocusListenerForTextComp(usernameDest);
    addFocusListenerForTextComp(passwordDest);

    addKeyListenerFor(usernameDest, !isDlg);
    addKeyListenerFor(passwordDest, !isDlg);

    addKeyListenerFor(databasesDest.getTextField(), !isDlg);
    addKeyListenerFor(serversDest.getTextField(), !isDlg);

    if (!isDlg) {
        addKeyListenerFor(loginBtn, true);
    }

    //autoLoginSourceCBX.setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.autologin", false));
    rememberUsernameSourceCBX
            .setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.rememberuserSource", false));
    rememberPasswordSourceCBX
            .setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.rememberpasswordSource", false));

    autoLoginDestCBX.setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.autologin2", false));
    rememberUsernameDestCBX
            .setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.rememberuserDest", false));
    rememberPasswordDestCBX
            .setSelected(AppPreferences.getLocalPrefs().getBoolean("convert.rememberpasswordDest", false));

    //        if (autoLoginSourceCBX.isSelected())
    //        {
    //            usernameSource.setText(AppPreferences.getLocalPrefs().get("convert.usernameSource", ""));
    //            passwordSource.setText(Encryption.decrypt(AppPreferences.getLocalPrefs().get(
    //                    "convert.passwordSource", "")));
    //            usernameSource.requestFocus();
    //
    //        } else
    //        {
    if (rememberUsernameSourceCBX.isSelected()) {
        usernameSource.setText(AppPreferences.getLocalPrefs().get("convert.usernameSource", ""));
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                passwordSource.requestFocus();
            }
        });

    }

    if (rememberPasswordSourceCBX.isSelected()) {
        passwordSource
                .setText(Encryption.decrypt(AppPreferences.getLocalPrefs().get("convert.passwordSource", "")));
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                loginBtn.requestFocus();
            }
        });

    }
    //}

    if (autoLoginDestCBX.isSelected()) {
        usernameDest.setText(AppPreferences.getLocalPrefs().get("convert.usernameDest", ""));
        passwordDest
                .setText(Encryption.decrypt(AppPreferences.getLocalPrefs().get("convert.passwordDest", "")));
        usernameDest.requestFocus();

    } else {
        if (rememberUsernameDestCBX.isSelected()) {
            usernameDest.setText(AppPreferences.getLocalPrefs().get("convert.usernameDest", ""));
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    passwordDest.requestFocus();
                }
            });

        }

        if (rememberPasswordDestCBX.isSelected()) {
            passwordDest.setText(
                    Encryption.decrypt(AppPreferences.getLocalPrefs().get("convert.passwordDest", "")));
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    loginBtn.requestFocus();
                }
            });

        }
    }
    cancelBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (dbConverterListener != null) {
                dbConverterListener.cancelled();
            }
        }
    });

    loginBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            doLogin();
        }
    });

    //HelpManager.registerComponent(helpBtn, "login");
    HelpMgr.registerComponent(helpBtn, "convert");

    //        autoLoginSourceCBX.addChangeListener(new ChangeListener()
    //        {
    //            public void stateChanged(ChangeEvent e)
    //            {
    //                if (autoLoginSourceCBX.isSelected())
    //                {
    //                    rememberUsernameSourceCBX.setSelected(true);
    //                    rememberPasswordSourceCBX.setSelected(true);
    //                }
    //                updateUIControls();
    //            }
    //
    //        });

    //        moreBtn.addActionListener(new ActionListener()
    //        {
    //            public void actionPerformed(ActionEvent e)
    //            {
    //                if (extraPanel.isVisible())
    //                {
    //                    if (dbDriverCBX.getSelectedIndex() != -1)
    //                    {
    //                        extraPanel.setVisible(false);
    //                        moreBtn.setIcon(forwardImgIcon);
    //                    }
    //
    //                } else
    //                {
    //                    extraPanel.setVisible(true);
    //                    moreBtn.setIcon(downImgIcon);
    //                }
    //                if (window != null)
    //                {
    //                    window.pack();
    //                }
    //            }
    //        });

    // Ask the PropertiesPickListAdapter to set the index from the prefs
    dbPickList.setSelectedIndex();
    svPickList.setSelectedIndex();

    dbDestPickList.setSelectedIndex();
    svDestPickList.setSelectedIndex();

    serversSource.getTextField().addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            updateUIControls();
        }
    });

    databasesSource.getTextField().addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            updateUIControls();
        }
    });

    // Layout the form
    JPanel p = new JPanel();//FormDebugPanel();
    PanelBuilder formBuilder = new PanelBuilder(
            new FormLayout("p,3dlu,max(220px;p):g,3dlu,p,3dlu,max(220px;p):g",
                    UIHelper.createDuplicateJGoodiesDef("p", "2dlu", 13)),
            p);
    CellConstraints cc = new CellConstraints();
    formBuilder.addSeparator(getResourceString("SOURCE_DB"), cc.xywh(1, 1, 3, 1));

    int y = 3;
    y = addLine("username", usernameSource, formBuilder, cc, y);
    y = addLine("password", passwordSource, formBuilder, cc, y);
    y = addLine("databases", databasesSource, formBuilder, cc, y);
    y = addLine("servers", serversSource, formBuilder, cc, y);
    //        formBuilder.addSeparator(getResourceString("extratitle"), cc.xywh(1, y, 3, 1));
    //        y +=2;
    y = addLine("driver", dbDriverCBX, formBuilder, cc, y);
    y = addLine(null, rememberUsernameSourceCBX, formBuilder, cc, y);
    y = addLine(null, rememberPasswordSourceCBX, formBuilder, cc, y);
    //y = addLine(null, autoLoginSourceCBX, formBuilder, cc, y);

    int x = 5;
    formBuilder.addSeparator(getResourceString("DEST_DB"), cc.xywh(x, 1, 3, 1));
    y = 3;

    y = addLine("username", usernameDest, formBuilder, cc, x, y);
    y = addLine("password", passwordDest, formBuilder, cc, x, y);
    y = addLine("databases", databasesDest, formBuilder, cc, x, y);
    y = addLine("servers", serversDest, formBuilder, cc, x, y);
    //        formBuilder.addSeparator(getResourceString("extratitle"), cc.xywh(1, y, 3, 1));
    //        y +=2;
    y = addLine("driver", dbDriverCBX2, formBuilder, cc, x, y);
    y = addLine(null, rememberUsernameDestCBX, formBuilder, cc, x, y);
    y = addLine(null, rememberPasswordDestCBX, formBuilder, cc, x, y);
    y = addLine(null, autoLoginDestCBX, formBuilder, cc, x, y);

    PanelBuilder extraPanelBlder = new PanelBuilder(new FormLayout("p,3dlu,max(220px;p):g", "p,2dlu,p,2dlu,p"));
    extraPanel = extraPanelBlder.getPanel();
    extraPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 4, 2));

    //formBuilder.add(moreBtn, cc.xy(1, y));
    //y += 2;

    //extraPanelBlder.addSeparator(getResourceString("extratitle"), cc.xywh(1, 1, 3, 1));
    //addLine("driver", dbDriverCBX, extraPanelBlder, cc, 3);
    //extraPanel.setVisible(false);

    //formBuilder.add(extraPanelBlder.getPanel(), cc.xywh(1, y, 3, 1));

    PanelBuilder outerPanel = new PanelBuilder(new FormLayout("p,3dlu,p:g", "p,2dlu,p,2dlu,p"), this);
    //JLabel icon = createLabel(IconManager.getIcon("SpecifyLargeIcon"));
    //icon.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));

    formBuilder.getPanel().setBorder(BorderFactory.createEmptyBorder(2, 5, 0, 5));

    //outerPanel.add(icon, cc.xy(1, 1));
    outerPanel.add(formBuilder.getPanel(), cc.xy(3, 1));
    outerPanel.add(ButtonBarFactory.buildOKCancelHelpBar(loginBtn, cancelBtn, helpBtn), cc.xywh(1, 3, 3, 1));
    outerPanel.add(statusBar, cc.xywh(1, 5, 3, 1));

    updateUIControls();
}

From source file:com.wizecommerce.hecuba.hector.HectorBasedHecubaClientManager.java

@Override
public void updateRow(K key, Map<String, Object> row, Map<String, Long> timestamps, Map<String, Integer> ttls)
        throws HectorException {
    final Mutator<K> m = HFactory.createMutator(keysp, keySerializer);

    List<String> secondaryColumnsChanged = null;
    List<String> secondaryIndexByColumnNameChanges = null;

    // check whether we have to set the timestamps.
    final boolean timestampsDefined = timestamps != null;

    // check whether we have to set the ttls.
    final boolean ttlsDefined = ttls != null;

    for (String columnName : row.keySet()) {
        final Object value = row.get(columnName);

        String valueToInsert = ClientManagerUtils.getInstance().convertValueForStorage(value);

        addInsertionToMutator(key, columnName, valueToInsert,
                timestampsDefined && timestamps.get(columnName) != null ? timestamps.get(columnName) : -1,
                ttlsDefined && ttls.get(columnName) != null ? ttls.get(columnName) : -1, m);

        // is this insertion involves a change to secondary indexes
        if (isSecondaryIndexByColumnNameAndValueEnabled) {
            if (Collections.binarySearch(columnsToIndexOnColumnNameAndValue, columnName) >= 0) {

                // doing a late initialization here.
                if (secondaryColumnsChanged == null) {
                    secondaryColumnsChanged = new ArrayList<String>();
                }/*  w  w w  . j a v a  2 s. c  o m*/

                secondaryColumnsChanged.add(columnName);
            }
        }

        // is this insertion involves changes to secondary index by column names.
        if (isSecondaryIndexByColumnNameEnabledForColumn(columnName)) {

            // doing a late initialization here.
            if (secondaryIndexByColumnNameChanges == null) {
                secondaryIndexByColumnNameChanges = new ArrayList<String>();
            }
            secondaryIndexByColumnNameChanges.add(columnName);
        }

    }

    if (isSecondaryIndexByColumnNameAndValueEnabled && secondaryColumnsChanged != null
            && secondaryColumnsChanged.size() > 0) {
        updateSecondaryIndexes(key, row, secondaryColumnsChanged, ttls);
    }

    if (isSecondaryIndexesByColumnNamesEnabled && secondaryIndexByColumnNameChanges != null
            && secondaryIndexByColumnNameChanges.size() > 0) {
        updateColumnNameBasedSecondaryIndices(key, secondaryIndexByColumnNameChanges, ttls);
    }

    try {
        final MutationResult mutationResult = m.execute();
        log.debug("Row Inserted into Cassandra. Exec Time = " + mutationResult.getExecutionTimeMicro()
                + ", Host used = " + mutationResult.getHostUsed());
    } catch (HectorException e) {
        log.debug("HecubaClientManager error while updating key " + key.toString());
        if (log.isDebugEnabled()) {
            logDownedHosts();
        }
        throw e;
    }

}

From source file:com.bigdata.dastor.io.SSTableReader.java

/** get the position in the index file to start scanning to find the given key (at most indexInterval keys away) */
private IndexSummary.KeyPosition getIndexScanPosition(DecoratedKey decoratedKey) {
    assert indexSummary.getIndexPositions() != null && indexSummary.getIndexPositions().size() > 0;
    int index = Collections.binarySearch(indexSummary.getIndexPositions(),
            new IndexSummary.KeyPosition(decoratedKey, -1));
    if (index < 0) {
        // binary search gives us the first index _greater_ than the key searched for,
        // i.e., its insertion position
        int greaterThan = (index + 1) * -1;
        if (greaterThan == 0)
            return null;
        return indexSummary.getIndexPositions().get(greaterThan - 1);
    } else {// w w w. j  a  va2s  .c  om
        return indexSummary.getIndexPositions().get(index);
    }
}

From source file:org.libreplan.business.calendars.entities.AvailabilityTimeLine.java

/**
 * Returns the insertion position for the interval. Inserting the interval
 * at that position guarantees that interval start is posterior or equal to
 * any previous interval start. If the next interval start is equal to the
 * interval, the length of the former is less than the latter
 *//*from   ww  w  . ja va 2  s .c  o m*/
private int findInsertionPosition(Interval interval) {
    int binarySearch = Collections.binarySearch(invalids, interval);

    return insertionPoint(binarySearch);
}

From source file:edu.ku.brc.dbsupport.DatabaseDriverInfo.java

/**
 * Locates a DatabaseDriverInfo object by name.
 * @param dbDrivers a list of drivers// ww  w.  j  av  a 2s . co  m
 * @param name the name to look up
 * @return the info object
 */
public static DatabaseDriverInfo getInfoByName(final Vector<DatabaseDriverInfo> dbDrivers, final String name) {
    int inx = Collections.binarySearch(dbDrivers, new DatabaseDriverInfo(name, null, null, false, null));
    return inx > -1 ? dbDrivers.get(inx) : null;
}

From source file:org.apache.cassandra.locator.TokenMetadata.java

public Token getPredecessor(Token token) {
    List tokens = sortedTokens();
    int index = Collections.binarySearch(tokens, token);
    assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndpointMap.keySet(), ", ");
    //        if (tokens.size() == 1) return (Token)(tokens.get(0));
    return (Token) (index == 0 ? tokens.get(tokens.size() - 1) : tokens.get(index - 1));
}

From source file:org.jfree.data.xy.XYSeries.java

/**
 * Adds a data item to the series and, if requested, sends a
 * {@link SeriesChangeEvent} to all registered listeners.
 *
 * @param item  the (x, y) item (<code>null</code> not permitted).
 * @param notify  a flag that controls whether or not a
 *                {@link SeriesChangeEvent} is sent to all registered
 *                listeners./* w ww.  j a  va 2s.com*/
 */
public void add(XYDataItem item, boolean notify) {

    if (item == null) {
        throw new IllegalArgumentException("Null 'item' argument.");
    }

    if (this.autoSort) {
        int index = Collections.binarySearch(this.data, item);
        if (index < 0) {
            this.data.add(-index - 1, item);
        } else {
            if (this.allowDuplicateXValues) {
                // need to make sure we are adding *after* any duplicates
                int size = this.data.size();
                while (index < size && item.compareTo(this.data.get(index)) == 0) {
                    index++;
                }
                if (index < this.data.size()) {
                    this.data.add(index, item);
                } else {
                    this.data.add(item);
                }
            } else {
                throw new SeriesException("X-value already exists.");
            }
        }
    } else {
        if (!this.allowDuplicateXValues) {
            // can't allow duplicate values, so we need to check whether
            // there is an item with the given x-value already
            int index = indexOf(item.getX());
            if (index >= 0) {
                throw new SeriesException("X-value already exists.");
            }
        }
        this.data.add(item);
    }
    if (getItemCount() > this.maximumItemCount) {
        this.data.remove(0);
    }
    if (notify) {
        fireSeriesChanged();
    }
}

From source file:org.jfree.data.xy.XYSeries.java

/**
 * Adds a data item to the series and, if requested, sends a
 * {@link SeriesChangeEvent} to all registered listeners.
 *
 * @param item  the (x, y) item (<code>null</code> not permitted).
 * @param notify  a flag that controls whether or not a
 *                {@link SeriesChangeEvent} is sent to all
 *                registered listeners.//from  www.  j  a  v a2s  .co m
 */
public void add(XYDataItem item, boolean notify) {
    if (item == null) {
        throw new IllegalArgumentException("Null 'item' argument.");
    }

    if (this.autoSort) {
        int index = Collections.binarySearch(this.data, item);
        if (index < 0) {
            this.data.add(-index - 1, item);
        } else {
            if (this.allowDuplicateXValues) {

                // need to make sure we are adding *after* any duplicates
                int size = this.data.size();
                while (index < size && item.compareTo(this.data.get(index)) == 0) {
                    index++;
                }
                if (index < this.data.size()) {
                    this.data.add(index, item);
                } else {
                    this.data.add(item);
                }
            } else {
                throw new SeriesException("X-value already exists.");
            }
        }
    } else {
        if (!this.allowDuplicateXValues) {

            // can't allow duplicate values, so we need to check whether
            // there is an item with the given x-value already
            int index = indexOf(item.getX());
            if (index >= 0) {
                throw new SeriesException("X-value already exists.");
            }
        }
        this.data.add(item);
    }
    if (getItemCount() > this.maximumItemCount) {
        this.data.remove(0);
    }
    if (notify) {
        fireSeriesChanged();
    }
}

From source file:org.apache.cassandra.locator.TokenMetadata.java

public Token getSuccessor(Token token) {
    List tokens = sortedTokens();
    int index = Collections.binarySearch(tokens, token);
    assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndpointMap.keySet(), ", ");
    //        if (tokens.size() == 1) return (Token)(tokens.get(0));
    return (Token) ((index == (tokens.size() - 1)) ? tokens.get(0) : tokens.get(index + 1));
}