Example usage for com.google.common.collect Iterables indexOf

List of usage examples for com.google.common.collect Iterables indexOf

Introduction

In this page you can find the example usage for com.google.common.collect Iterables indexOf.

Prototype

public static <T> int indexOf(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns the index in iterable of the first element that satisfies the provided predicate , or -1 if the Iterable has no such elements.

Usage

From source file:co.freeside.betamax.tape.MemoryTape.java

private synchronized int findMatch(final Request request) {
    return Iterables.indexOf(interactions, new Predicate<RecordedInteraction>() {
        @Override/*from   w  w w .  ja  v  a2 s. c  o m*/
        public boolean apply(RecordedInteraction input) {
            return matchRule.isMatch(request, input.getRequest());
        }
    });
}

From source file:org.sonar.server.debt.DebtModelOperations.java

@CheckForNull
private CharacteristicDto findCharacteristicToSwitchWith(final CharacteristicDto dto,
        final boolean moveUpOrDown, SqlSession session) {
    // characteristics should be sort by 'order'
    List<CharacteristicDto> rootCharacteristics = dbClient.debtCharacteristicDao()
            .selectEnabledRootCharacteristics(session);
    int currentPosition = Iterables.indexOf(rootCharacteristics, new Predicate<CharacteristicDto>() {
        @Override/* w  w  w.  j av a2 s  . c  o  m*/
        public boolean apply(@Nullable CharacteristicDto input) {
            return input != null && input.getKey().equals(dto.getKey());
        }
    });
    Integer nextPosition = moveUpOrDown ? (currentPosition > 0 ? currentPosition - 1 : null)
            : (currentPosition < rootCharacteristics.size() - 1 ? currentPosition + 1 : null);
    return nextPosition != null ? Iterables.get(rootCharacteristics, nextPosition) : null;
}

From source file:org.polymap.core.data.ui.featuretable.DeferredFeatureContentProvider2.java

protected int doFindElement(Object[] elms, Object search) {
    assert search != null;
    if (search instanceof IFeatureTableElement && elms != null) {
        return Iterables.indexOf(Arrays.asList(elms), Predicates.equalTo(search));
    }// w  w  w.jav  a  2s . com
    return -1;
}

From source file:com.microsoftopentechnologies.intellij.forms.TableForm.java

public TableForm() {
    final TableForm form = this;
    this.setResizable(false);
    this.setModal(true);
    this.setTitle("Create new table");
    this.setContentPane(mainPanel);

    createButton.setEnabled(false);//from   www  .  ja  v  a2  s  .  com

    tableNameTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent keyEvent) {
            super.keyTyped(keyEvent);

            createButton.setEnabled(!tableNameTextField.getText().isEmpty());
        }
    });

    final PermissionItem[] tablePermissions = PermissionItem.getTablePermissions();

    insertPermisssionComboBox.setModel(new DefaultComboBoxModel(tablePermissions));
    deletePermissionComboBox.setModel(new DefaultComboBoxModel(tablePermissions));
    updatePermissionComboBox.setModel(new DefaultComboBoxModel(tablePermissions));
    readPermissionComboBox.setModel(new DefaultComboBoxModel(tablePermissions));

    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            form.setVisible(false);
            form.dispose();
        }
    });

    createButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        TablePermissions tablePermissions = new TablePermissions();

                        tablePermissions.setDelete(
                                ((PermissionItem) deletePermissionComboBox.getSelectedItem()).getType());
                        tablePermissions.setUpdate(
                                ((PermissionItem) updatePermissionComboBox.getSelectedItem()).getType());
                        tablePermissions
                                .setRead(((PermissionItem) readPermissionComboBox.getSelectedItem()).getType());
                        tablePermissions.setInsert(
                                ((PermissionItem) insertPermisssionComboBox.getSelectedItem()).getType());

                        final String tableName = tableNameTextField.getText().trim();

                        if (!tableName.matches("^[A-Za-z][A-Za-z0-9_]+")) {
                            JOptionPane.showMessageDialog(form,
                                    "Invalid table name. Table name must start with a letter, \n"
                                            + "contain only letters, numbers, and underscores.",
                                    "Error creating the table", JOptionPane.ERROR_MESSAGE);
                            return;
                        }

                        int tableNameIndex = -1;
                        if (existingTableNames != null) {
                            tableNameIndex = Iterables.indexOf(existingTableNames, new Predicate<String>() {
                                @Override
                                public boolean apply(String name) {
                                    return tableName.equalsIgnoreCase(name);
                                }
                            });
                        }

                        if (tableNameIndex != -1) {
                            JOptionPane.showMessageDialog(form,
                                    "Invalid table name. A table with that name already exists in this service.",
                                    "Error creating the table", JOptionPane.ERROR_MESSAGE);
                            return;
                        }

                        form.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                        if (editingTable == null) {
                            AzureRestAPIManager.getManager().createTable(subscriptionId, serviceName, tableName,
                                    tablePermissions);
                        } else {
                            AzureRestAPIManager.getManager().updateTable(subscriptionId, serviceName, tableName,
                                    tablePermissions);
                        }
                        if (afterSave != null)
                            afterSave.run();

                        form.setVisible(false);
                        form.dispose();
                        form.setCursor(Cursor.getDefaultCursor());

                    } catch (Throwable e) {
                        form.setCursor(Cursor.getDefaultCursor());
                        UIHelper.showException("Error creating table", e);
                    }

                }
            });
        }
    });
}

From source file:com.microsoft.intellij.forms.TableForm.java

@Nullable
@Override//  w ww  . j  ava  2s  .c  om
protected ValidationInfo doValidate() {
    final String tableName = tableNameTextField.getText().trim();

    if (!tableName.matches("^[A-Za-z][A-Za-z0-9_]+")) {
        return new ValidationInfo("Invalid table name. Table name must start with a letter, \n"
                + "contain only letters, numbers, and underscores.", tableNameTextField);
    }

    int tableNameIndex = -1;
    if (existingTableNames != null) {
        tableNameIndex = Iterables.indexOf(existingTableNames, new Predicate<String>() {
            @Override
            public boolean apply(String name) {
                return tableName.equalsIgnoreCase(name);
            }
        });
    }

    if (tableNameIndex != -1) {
        return new ValidationInfo("Invalid table name. A table with that name already exists in this service.",
                tableNameTextField);
    }

    return null;
}

From source file:swingn.ui.TableView.java

protected void parse(Element<?> cell) {
    Table.Row row = (Table.Row) cell.parent();
    int colIdx = Iterables.indexOf(row, Predicates.<Element<?>>equalTo(cell));
    int rowIdx = Iterables.indexOf(table.rows, Predicates.<Element<?>>equalTo(row));

    Renderers.Cell renderer = _renderers[colIdx];

    // TODO: should we catch exceptions here?
    Object value = renderer.parse(this, cell, rowIdx, colIdx);

    if (value == null) {
        // something went wrong, value couldn't be parsed
        // TODO: maybe refresh the cell here? show a warning box?
        return;/* w  ww  . j a v  a 2 s. c  o  m*/
    }

    ((TableModel.Editable) _model).setValueAt(value, rowIdx, modelColumnIndex(colIdx));
}

From source file:brooklyn.location.docker.DockerContainerLocation.java

private void parseDockerCallback(String commandString) {
    List<String> tokens = DockerCallbacks.PARSER.splitToList(commandString);
    int callback = Iterables.indexOf(tokens, Predicates.equalTo(DockerCallbacks.DOCKER_HOST_CALLBACK));
    if (callback == -1) {
        LOG.warn("Could not find callback token: {}", commandString);
        throw new IllegalStateException("Cannot find callback token in command line");
    }/*from w w  w  .  j  a  va2s. co m*/
    String command = tokens.get(callback + 1);
    LOG.info("Executing callback for {}: {}", getOwner(), command);
    if (DockerCallbacks.COMMIT.equalsIgnoreCase(command)) {
        String containerId = getOwner().getContainerId();
        String imageName = getOwner().getAttribute(DockerContainer.IMAGE_NAME);
        String output = getOwner().getDockerHost()
                .runDockerCommandTimeout(format("commit %s %s", containerId, imageName), Duration.minutes(20));
        String imageId = DockerUtils.checkId(output);
        ((EntityLocal) getOwner().getRunningEntity()).setAttribute(DockerContainer.IMAGE_ID, imageId);
        ((EntityLocal) getOwner()).setAttribute(DockerContainer.IMAGE_ID, imageId);
        getOwner().getDockerHost().getDynamicLocation().markImage(imageName);
    } else if (DockerCallbacks.PUSH.equalsIgnoreCase(command)) {
        String imageName = getOwner().getAttribute(DockerContainer.IMAGE_NAME);
        getOwner().getDockerHost().runDockerCommand(format("push %s", imageName));
    } else if (DockerCallbacks.SUBNET_ADDRESS.equalsIgnoreCase(command)) {
        String address = getOwner().getAttribute(Attributes.SUBNET_ADDRESS);
        ((EntityLocal) getOwner().getRunningEntity()).setAttribute(Attributes.SUBNET_ADDRESS, address);
        ((EntityLocal) getOwner().getRunningEntity()).setAttribute(Attributes.SUBNET_HOSTNAME, address);
    } else {
        LOG.warn("Unknown Docker host command: {}", command);
    }
}

From source file:com.linkedin.flashback.SceneAccessLayer.java

/**
 * find matched request from scene//from   ww  w  .ja va  2s .c o  m
 * @param request incoming request that we'd like match in existing scene
 * @return position of list of HttpExchanges from the scene. return -1 if no match found
 *
 * */
private int findMatchRequest(final RecordedHttpRequest request) {
    if (_scene.isSequential()) {
        List<RecordedHttpExchange> exchangeList = _scene.getRecordedHttpExchangeList();
        // In sequential playback mode, only test the request at the current sequence index
        if (_sequencePosition < exchangeList.size()
                && _matchRule.test(request, exchangeList.get(_sequencePosition).getRecordedHttpRequest())) {
            return _sequencePosition;
        }
        return -1;
    } else {
        return Iterables.indexOf(_scene.getRecordedHttpExchangeList(),
                input -> _matchRule.test(request, input.getRecordedHttpRequest()));
    }
}

From source file:org.zanata.webtrans.server.rpc.GetTransUnitListHandler.java

private GetTransUnitListResult transformToTransUnits(GetTransUnitList action, HLocale hLocale,
        List<HTextFlow> textFlows, int targetOffset, int targetPage) {
    List<TransUnit> units = Lists.transform(textFlows,
            new HTextFlowToTransUnitFunction(hLocale, transUnitTransformer));
    int gotoRow = 0;
    if (action.getTargetTransUnitId() != null) {
        int row = Iterables.indexOf(units, new FindByTransUnitIdPredicate(action.getTargetTransUnitId()));
        if (row != -1) {
            gotoRow = row;//from  w  w w.  j  a v  a 2s .  c o m
        }
    }
    // stupid GWT RPC can't handle
    // com.google.common.collect.Lists$TransformingRandomAccessList
    return new GetTransUnitListResult(action.getDocumentId(), Lists.newArrayList(units), gotoRow, targetOffset,
            targetPage);
}

From source file:com.publicuhc.pluginframework.routing.DefaultRouter.java

/**
 * On tab complete. The final arg is the one we want to match against, can be empty
 *///from   w w w.  j  av a2 s.c o m
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
    Preconditions.checkArgument(args.length > 0);
    List<String> tabCompleteList = Lists.newArrayList();

    List<String> route = Lists.newArrayList(args);

    //get the item to tab complete and remove it from the list
    String partial = route.get(route.size() - 1);
    route = route.subList(0, route.size() - 1);

    //check if already have any flags
    int index = Iterables.indexOf(route, new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return input.startsWith("-");
        }
    });

    //if there are any options remove everything past the first one
    if (index > -1) {
        route = route.subList(0, index);
    }

    //get all of the routes for the command
    Collection<CommandRoute> allRoutes = commands.get(command.getName());

    //all of the subroutes
    Collection<CommandRoute> subroutes = Collections2.filter(allRoutes, new SubroutePredicate(route));

    //exact matches
    Collection<CommandRoute> exacts = Collections2.filter(allRoutes, new ExactRouteMatchPredicate(route));

    for (CommandRoute r : exacts) {
        for (String key : r.getOptionDetails().recognizedOptions().keySet()) {
            if (!key.equals("[arguments]")) {
                tabCompleteList.add("-" + key);
            }
        }
    }

    for (CommandRoute r : subroutes) {
        //this should pass as the predicate makes sure there is a next arg
        String nextInSubroute = r.getStartsWith()[route.size()];
        tabCompleteList.add(nextInSubroute);
    }

    List<String> actualComplete = Lists.newArrayList();
    StringUtil.copyPartialMatches(partial, tabCompleteList, actualComplete);
    return actualComplete;
}