Example usage for java.util List indexOf

List of usage examples for java.util List indexOf

Introduction

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

Prototype

int indexOf(Object o);

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:com.ikon.servlet.frontend.ThesaurusServlet.java

@Override
public List<String> getKeywords(final String filter) throws OKMException {
    log.debug("getKeywords({})", filter);
    List<String> keywordList = new ArrayList<String>();
    List<String> keywords = RDFREpository.getInstance().getKeywords();
    int index = -1;
    int size = keywords.size();
    updateSessionManager();/*from ww w  . j  av a2s  .  com*/

    // Keywords list is an ordered list
    String value = (String) CollectionUtils.find(keywords, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            String key = (String) arg0;
            if (key.toLowerCase().startsWith(filter)) {
                return true;
            } else {
                return false;
            }
        }
    });

    if (value != null) {
        index = keywords.indexOf(value);
    }

    if (index >= 0) {
        while (size > index && keywords.get(index).toLowerCase().startsWith(filter)) {
            keywordList.add(keywords.get(index));
            index++;
        }
    }

    log.debug("getKeywords: {}", keywordList);
    return keywordList;
}

From source file:com.appdynamics.monitors.hadoop.communicator.AmbariCommunicator.java

/**
 * Parses a JSON Reader object as host metrics and collect host state plus host metrics.
 * Prefixes metric name with <code>hierarchy</code>.
 * @see #getAllMetrics(java.util.Map, String)
 *
 * @param response/*from w ww  . j a v  a2  s .  c o  m*/
 * @param hierarchy
 */
private void getHostMetrics(Reader response, String hierarchy) {
    try {
        Map<String, Object> json = (Map<String, Object>) parser.parse(response, simpleContainer);
        try {
            Map hostInfo = (Map) json.get("Hosts");
            String hostName = (String) hostInfo.get("host_name");
            String hostState = (String) hostInfo.get("host_state");

            List<String> states = new ArrayList<String>();
            states.add("INIT");
            states.add("WAITING_FOR_HOST_STATUS_UPDATES");
            states.add("HEALTHY");
            states.add("HEARTBEAT_LOST");
            states.add("UNHEALTHY");
            metrics.put(hierarchy + "|" + hostName + "|state", states.indexOf(hostState));

            Map hostMetrics = (Map) json.get("metrics");

            //remove non metric data
            hostMetrics.remove("boottime");

            Iterator<Map.Entry> iter = hostMetrics.entrySet().iterator();
            while (iter.hasNext()) {
                if (!xmlParser.isIncludeHostMetrics((String) iter.next().getKey())) {
                    iter.remove();
                }
            }

            getAllMetrics(hostMetrics, hierarchy + "|" + hostName);
        } catch (Exception e) {
            logger.error("Failed to parse host metrics: " + stackTraceToString(e));
        }
    } catch (Exception e) {
        logger.error("Failed to get response for host metrics: " + stackTraceToString(e));
    }
}

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

private void updateConfig() {
    try {/*from   w ww.  ja  va2s. co  m*/
        List<String> lines = FileUtils.readLines(configFile, Charsets.UTF_8);
        int index;
        if (core.getConfig().getInt("version") == 13) {
            core.log("The config file is up to date.");
        } else {
            switch (core.getConfig().getInt("version")) {
            case 9:
                index = lines.indexOf("MySQL:") - 2;
                lines.addAll(index, Arrays.asList(
                        "# Here you can enable Vault to make this plugin manage all the Vault transactions.",
                        "Vault:", "  Use: false", "  # Names used by vault for the currency.", "  Name:",
                        "    Singular: 'Coin'", "    Plural: 'Coins'", ""));
                index = lines.indexOf("version: 9");
                lines.set(index, "version: 10");
                core.log("Configuraton file updated to v10");
                break;
            case 10:
                index = lines.indexOf("    Close:") + 1;
                lines.addAll(index, Arrays.asList(
                        "      # To see all possible values check https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Material.html",
                        "      Material: REDSTONE_BLOCK", "      Name: '&c&lClose'", "      Lore:",
                        "      - ''", "      - '&7Click me to close this gui'"));
                index = lines.indexOf("version: 10");
                lines.set(index, "version: 11");
                core.log("Configuraton file updated to v11");
                break;
            case 11:
                index = lines.indexOf("  Executor Sign:") + 5;
                lines.addAll(index, Arrays.asList(
                        "  # If you want the users to be created when they join to the server, enable this,",
                        "  # otherwise the players will be created when his coins are modified or consulted",
                        "  # to the database for the first time (recommended for big servers).",
                        "  Create Join: false"));
                index = lines.indexOf("version: 11");
                lines.set(index, "version: 12");
                core.log("Configuration file updated to v12");
                break;
            case 12:
                index = lines.indexOf("version: 12");
                lines.set(index, "version: 13");
                core.log("Configuration file updated to v13");
                break;
            default:
                core.log(
                        "Seems that you hava a too old version of the config or you canged this to another number >:(");
                core.log(
                        "We can't update it, if is a old version you should try to update it slow and not jump from a version to another, keep in mind that we keep track of the last 3 versions of the config to update.");
                break;
            }
        }
        FileUtils.writeLines(configFile, lines);
        core.getConfig().reload();
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the config file.");
        core.debug(ex.getMessage());
    }
}

From source file:es.udc.gii.common.eaf.algorithm.operator.reproduction.mutation.de.mutationStrategy.BestDEMutationStrategy.java

@Override
public Individual getMutatedIndividual(EvolutionaryAlgorithm algorithm, Individual target) {

    BestIndividualSpecification bestSpec = new BestIndividualSpecification();
    double[] base;
    List<Individual> individuals;
    List<Individual> listInd;
    List<Integer> index_list;
    int randomPos;
    double auxGeneValue, x1, x2;
    double F;//from   ww w.  j ava 2  s .  c  o m

    F = this.getFPlugin().get(algorithm);
    individuals = algorithm.getPopulation().getIndividuals();
    base = ((Individual) IndividualsProductTrader
            .get(bestSpec, algorithm.getPopulation().getIndividuals(), 1, algorithm.getComparator()).get(0))
                    .getChromosomeAt(0);
    index_list = new ArrayList<>();
    index_list.add(individuals.indexOf(base));

    //se eligen los vectores diferenciales:
    listInd = new ArrayList<>();

    for (int i = 0; i < this.getDiffVector() * 2; i++) {

        do {

            randomPos = (int) EAFRandom.nextInt(individuals.size());

        } while (index_list.contains(randomPos));

        listInd.add(individuals.get(randomPos));
        index_list.add(randomPos);

    }

    if (base != null) {
        //Recorremos el numero de genes:
        for (int i = 0; i < base.length; i++) {

            auxGeneValue = base[i];

            for (int j = 0; j < this.getDiffVector(); j += 2) {

                x1 = listInd.get(j).getChromosomeAt(0)[i];
                x2 = listInd.get(j + 1).getChromosomeAt(0)[i];

                auxGeneValue += F * (x1 - x2);

            }

            base[i] = auxGeneValue;

        }
    }

    Individual mutatedIndividual = new Individual();
    mutatedIndividual.setChromosomeAt(0, base);

    return mutatedIndividual;
}

From source file:com.vmware.vfabric.ide.eclipse.tcserver.internal.ui.TcStaticResourcesEditorSection.java

@Override
public void createSection(Composite parent) {
    super.createSection(parent);
    FormToolkit toolkit = getFormToolkit(parent.getDisplay());

    Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED
            | ExpandableComposite.TITLE_BAR | Section.DESCRIPTION | ExpandableComposite.FOCUS_TITLE);
    section.setText("Reload Behavior");
    section.setDescription(/* w ww .  j  a  v a  2 s.  c o m*/
            "Configure module reload behavior on changes of project resources.\n\nDefine patterns for files that should be copied to deployed applications without triggering a reload. Spring XML configuration files are handled separately.");

    section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    Composite composite = toolkit.createComposite(section);
    GridLayout layout = new GridLayout();
    layout.numColumns = 2;
    layout.marginHeight = 5;
    layout.marginWidth = 1;
    layout.verticalSpacing = 5;
    layout.horizontalSpacing = 10;
    composite.setLayout(layout);
    composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
    toolkit.paintBordersFor(composite);
    section.setClient(composite);

    enableButton = toolkit.createButton(composite,
            "Enable controlled reload (requires Auto Reload to be disabled to take effect)", SWT.CHECK);
    GridDataFactory.fillDefaults().span(2, 1).applyTo(enableButton);
    enableButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            if (updating) {
                return;
            }
            try {
                updating = true;
                boolean enabled = enableButton.getSelection();
                execute(new ModifyEnhancedRedeployCommand(serverWorkingCopy, enabled));
                try {
                    TcServerConfiguration configuration = serverWorkingCopy.getTomcatConfiguration();
                    List<?> list = serverWorkingCopy.getTomcatConfiguration().getWebModules();
                    int i = 0;
                    Iterator iterator = list.iterator();
                    while (iterator.hasNext()) {
                        WebModule module = (WebModule) iterator.next();
                        WebModule newModule = new WebModule(module.getPath(), module.getDocumentBase(),
                                module.getMemento(), !enabled);
                        execute(new ModifyWebModuleCommand(serverWorkingCopy.getTomcatConfiguration(), i,
                                newModule));
                        i++;
                    }
                } catch (Exception e) {
                    return;
                }
            } finally {
                updating = false;
            }
        }
    });

    filenameTable = toolkit.createTable(composite, SWT.SINGLE | SWT.V_SCROLL | SWT.FULL_SELECTION);
    GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
    data.heightHint = 130;
    filenameTable.setLayoutData(data);
    filenamesTableViewer = new TableViewer(filenameTable);
    contentProvider = new StaticFilenamesContentProvider();
    filenamesTableViewer.setContentProvider(contentProvider);
    filenamesTableViewer.setLabelProvider(new FilenameLabelProvider());

    filenamesTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            Object obj = ((IStructuredSelection) event.getSelection()).getFirstElement();
            deleteButton.setEnabled(obj != null);
            updateButtons(obj);
        }
    });

    Composite buttonComposite = new Composite(composite, SWT.NONE);
    GridLayout buttonLayout = new GridLayout(1, true);
    buttonLayout.marginWidth = 0;
    buttonLayout.marginHeight = 0;
    buttonComposite.setLayout(buttonLayout);
    GridDataFactory.fillDefaults().applyTo(buttonComposite);

    addButton = toolkit.createButton(buttonComposite, "Add...", SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(addButton);
    addButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (updating) {
                return;
            }

            InputDialog dialog = new InputDialog(getShell(), "New filename pattern",
                    "Enter a new filename pattern for static resources (wildcards such as '*' and '?' are supported):",
                    "", new IInputValidator() {

                        public String isValid(String newText) {
                            if (StringUtils.isBlank(newText)) {
                                return "Pattern can't be empty";
                            }
                            return null;
                        }
                    });
            if (dialog.open() == Dialog.OK) {
                updating = true;
                List<Object> filenames = new ArrayList<Object>(
                        Arrays.asList(contentProvider.getElements(server)));
                filenames.add(dialog.getValue());
                execute(new ModifyStaticResourcesCommand(serverWorkingCopy, StringUtils.join(filenames, ",")));
                filenamesTableViewer.setInput(server);
                filenamesTableViewer.setSelection(new StructuredSelection(dialog.getValue()));
                // update buttons
                updating = false;
            }
        }
    });

    deleteButton = toolkit.createButton(buttonComposite, "Delete", SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(deleteButton);
    deleteButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object selectedArtefact = ((IStructuredSelection) filenamesTableViewer.getSelection())
                    .getFirstElement();
            if (updating) {
                return;
            }
            updating = true;
            List<Object> filenames = new ArrayList<Object>(Arrays.asList(contentProvider.getElements(server)));
            filenames.remove(selectedArtefact);
            execute(new ModifyStaticResourcesCommand(serverWorkingCopy, StringUtils.join(filenames, ",")));
            filenamesTableViewer.setInput(server);
            // update buttons
            updating = false;
        }
    });

    upButton = toolkit.createButton(buttonComposite, "Up", SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(upButton);
    upButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object selectedArtefact = ((IStructuredSelection) filenamesTableViewer.getSelection())
                    .getFirstElement();
            List<Object> modules = new ArrayList<Object>();
            modules.addAll(Arrays.asList(contentProvider.getElements(server)));
            int index = modules.indexOf(selectedArtefact);
            modules.remove(selectedArtefact);
            modules.add(index - 1, selectedArtefact);
            if (updating) {
                return;
            }
            updating = true;
            execute(new ModifyStaticResourcesCommand(serverWorkingCopy, StringUtils.join(modules, ",")));
            filenamesTableViewer.setInput(server);
            updateButtons(selectedArtefact);
            updating = false;
        }
    });

    downButton = toolkit.createButton(buttonComposite, "Down", SWT.PUSH);
    GridDataFactory.fillDefaults().applyTo(downButton);
    downButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object selectedArtefact = ((IStructuredSelection) filenamesTableViewer.getSelection())
                    .getFirstElement();
            List<Object> modules = new ArrayList<Object>();
            modules.addAll(Arrays.asList(contentProvider.getElements(server)));
            int index = modules.indexOf(selectedArtefact);
            modules.remove(selectedArtefact);
            modules.add(index + 1, selectedArtefact);
            if (updating) {
                return;
            }
            updating = true;
            execute(new ModifyStaticResourcesCommand(serverWorkingCopy, StringUtils.join(modules, ",")));
            filenamesTableViewer.setInput(server);
            updateButtons(selectedArtefact);
            updating = false;
        }
    });

    FormText restoreDefault = toolkit.createFormText(composite, true);
    restoreDefault.setText("<form><p><a href=\"exportbundle\">Restore default</a> filename patterns</p></form>",
            true, false);
    restoreDefault.addHyperlinkListener(new HyperlinkAdapter() {
        @Override
        public void linkActivated(HyperlinkEvent e) {
            updating = true;
            execute(new ModifyStaticResourcesCommand(serverWorkingCopy, TcServer.DEFAULT_STATIC_FILENAMES));
            filenamesTableViewer.setInput(server);
            updating = false;
        }
    });
    updateEnablement();
    initialize();
}

From source file:com.jaspersoft.studio.components.chart.wizard.fragments.data.DSPie.java

protected Control createChartTop(Composite composite) {
    Composite yCompo = new Composite(composite, SWT.NONE);
    yCompo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
    yCompo.setLayout(new GridLayout(10, false));

    Label lbl = new Label(yCompo, SWT.NONE);
    lbl.setText(Messages.DSCategory_seriesLabel);
    lbl.setToolTipText(Messages.DSPie_seriesTooltip);
    seriesCombo = new Combo(yCompo, SWT.READ_ONLY | SWT.BORDER);
    seriesCombo.setToolTipText(Messages.DSPie_seriesTooltip);
    GridData gd = new GridData(GridData.FILL_HORIZONTAL);
    gd.widthHint = 300;/*from ww w  . j av  a 2s  .co m*/
    seriesCombo.setLayoutData(gd);
    seriesCombo.setItems(new String[] { "series 1" }); //$NON-NLS-1$
    seriesCombo.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent e) {
            handleSelectSeries(seriesCombo.getSelectionIndex());
            obtn.setSelection(false);
            valueWidget.setEnabled(true);
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });

    final Button btn = new Button(yCompo, SWT.PUSH | SWT.FLAT);
    btn.setText("..."); //$NON-NLS-1$
    btn.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent e) {
            PieSerie serie = new PieSerie();
            SeriesDialog<JRPieSeries> dlg = new SeriesDialog<JRPieSeries>(btn.getShell(), serie);
            dlg.setExpressionContext(expContext);
            List<JRPieSeries> oldList = dataset.getSeriesList();
            int oldsel = seriesCombo.getSelectionIndex();
            JRPieSeries selected = null;
            if (oldsel >= 0)
                selected = oldList.get(oldsel);
            serie.setList(oldList);
            if (dlg.open() == Window.OK) {
                List<JRPieSeries> newlist = serie.getList();
                for (JRPieSeries item : dataset.getSeries())
                    dataset.removePieSeries(item);
                for (JRPieSeries item : serie.getList())
                    dataset.addPieSeries(item);

                int sel = selected != null && newlist.indexOf(selected) >= 0 ? newlist.indexOf(selected) : 0;
                setSeries(sel);
            }
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });

    hyperlinkBtn = new Button(yCompo, SWT.PUSH | SWT.FLAT);
    hyperlinkBtn.setSelection(false);
    hyperlinkBtn.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent e) {
            int selection = seriesCombo.getSelectionIndex();
            JRDesignPieSeries serie = null;
            if (selection >= 0 && selection < dataset.getSeriesList().size())
                serie = (JRDesignPieSeries) dataset.getSeriesList().get(selection);
            if (serie != null) {
                MHyperLink hyperLinkElement = null;
                JRHyperlink hyperlink = serie.getSectionHyperlink();
                if (hyperlink != null) {
                    hyperLinkElement = new MHyperLink((JRHyperlink) hyperlink.clone());
                } else {
                    hyperLinkElement = new MHyperLink(new JRDesignHyperlink());
                }
                String dialogTitle = MessageFormat.format(Messages.HyperlinkDialog_hyperlinkDialogTitle,
                        seriesCombo.getText());
                HyperlinkPage dlg = new HyperlinkPage(hyperlinkBtn.getShell(), hyperLinkElement, dialogTitle);
                int operationResult = dlg.open();
                if (operationResult == Window.OK) {
                    serie.setSectionHyperlink((JRHyperlink) dlg.getElement().getValue());
                } else if (operationResult == IDialogConstants.ABORT_ID) {
                    serie.setSectionHyperlink(null);
                }
            }
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            widgetSelected(e);
        }
    });

    return yCompo;
}

From source file:gov.nih.nci.caarray.plugins.illumina.CsvDataHandler.java

private List<String> getSampleNamesFromGroupId(List<String> headers, DelimitedFileReader reader)
        throws IOException {
    final Set<String> nameSet = new HashSet<String>();
    final List<String> names = new ArrayList<String>();
    final int position = headers.indexOf(GROUP_ID_HEADER);
    while (reader.hasNextLine()) {
        final String groupId = reader.nextLine().get(position);
        if (!nameSet.contains(groupId)) {
            nameSet.add(groupId);//from   w  w  w.ja  v a2  s.co  m
            names.add(groupId);
        }
    }
    return names;
}

From source file:net.brewspberry.front.JFreeGraphServlet.java

/**
 * Converts List of {@link TemperatureMeasurement}
 * /*  ww w.j a v a 2s .  co m*/
 * @param tempList
 * @param probesList
 * @return
 */
public List<String[]> parseTemperatureMeasurements(List<TemperatureMeasurement> tempList,
        List<String> probesList) {
    List<String[]> result = new ArrayList<String[]>();

    Iterator<TemperatureMeasurement> it = tempList.iterator();

    while (it.hasNext()) {
        String[] array = new String[probesList.size() + 5];

        TemperatureMeasurement temp = it.next();

        int index = probesList.indexOf(temp.getTmes_probe_name()) + 5;

        array[0] = temp.getTmes_date().toString();
        array[1] = temp.getTmes_brassin().getBra_id().toString();
        array[2] = temp.getTmes_etape().getEtp_id().toString();
        array[3] = String.valueOf(temp.getTmes_actioner().getAct_id());
        array[4] = String.valueOf(temp.getTmes_probeUI());
        array[index] = temp.getTmes_value().toString();

        String toLog = "Line : ";
        for (String el : array) {

            toLog = toLog + " | " + el;

        }

        logger.fine(toLog);
        result.add(array);
    }

    return result;

}

From source file:com.google.gdt.eclipse.designer.mobile.preferences.device.DevicesPreferencePage.java

/**
 * Moves selected elements up/down.//from w  w w  .j  a  va 2 s. co  m
 */
private void onMove(int delta) {
    m_viewer.getTree().setRedraw(false);
    try {
        for (Object element : getSelectedElements()) {
            if (element instanceof CategoryInfo) {
                CategoryInfo category = (CategoryInfo) element;
                List<CategoryInfo> categories = DeviceManager.getCategories();
                int index = categories.indexOf(element);
                int targetIndex = index + delta;
                CategoryInfo nextCategory = targetIndex < categories.size()
                        ? (CategoryInfo) categories.get(targetIndex)
                        : null;
                commands_add(new CategoryMoveCommand(category, nextCategory));
            } else if (element instanceof DeviceInfo) {
                DeviceInfo device = (DeviceInfo) element;
                CategoryInfo category = device.getCategory();
                List<DeviceInfo> devices = category.getDevices();
                int index = devices.indexOf(device);
                if (index + delta < devices.size()) {
                    commands_add(new DeviceMoveCommand(device, category, devices.get(index + delta)));
                } else {
                    commands_add(new DeviceMoveCommand(device, category, null));
                }
            }
        }
        refreshViewer();
        updateButtons();
    } finally {
        m_viewer.getTree().setRedraw(true);
    }
}

From source file:fr.acxio.tools.agia.alfresco.ListFieldSetToNodeProcessor.java

@Override
public NodeList process(List<FieldSet> sItems) throws BindException {
    NodeList aResult = null;// w w w  . j  a  v a2 s. c o  m
    if (sItems != null) {
        for (FieldSet aFieldSet : sItems) {
            if (aResult == null) {
                aResult = objectToNodeList(aFieldSet);
            } else {
                // Rebase new nodes on existing folders
                NodeList aNewNodeList = objectToNodeList(aFieldSet);
                List<String> aExistingPaths = new ArrayList<String>(aResult.size());
                for (Node aNode : aResult) {
                    aExistingPaths.add(aNode.getPath());
                }
                String aNewNodePath;
                for (Node aNewNode : aNewNodeList) {
                    aNewNodePath = aNewNode.getPath();

                    if (!aExistingPaths.contains(aNewNodePath)) {
                        aResult.add(aNewNode);
                        aExistingPaths.add(aNewNodePath);
                        if (aNewNode.getParent() != null) {
                            int aParentIndex = aExistingPaths.indexOf(aNewNode.getParent().getPath());
                            Folder aParent = (Folder) aResult.get(aParentIndex);
                            aNewNode.setParent(aParent);
                            if (aNewNode instanceof Document) {
                                aParent.addDocument((Document) aNewNode);
                            } else if (aNewNode instanceof Folder) {
                                aParent.addFolder((Folder) aNewNode);
                            }
                        }

                    }
                }
            }
        }
    }
    return aResult;
}