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:org.apache.ode.jacob.soup.jackson.JacksonSoupTest.java

@Test
public void testSimpleHelloWorldSerializeAndDeserialize() throws Exception {
    List<String> states = new ArrayList<String>();

    JacobVPU vpu = new JacobVPU();
    vpu.setContext(queue);//from   ww w . j a v  a2  s .c  o m
    vpu.inject(new HelloWorld() {
        @Override
        public void run() {
            simpleHelloWorld();
        }
    });

    int i = 0;
    while (vpu.execute()) {
        String ser = mapper.writeValueAsString(queue);
        states.add(ser);
        i++;
    }
    Assert.assertEquals(9, i);

    // deserialize
    for (String state : states) {
        vpu.setContext(mapper.readValue(state, JacksonExecutionQueueImpl.class));
        i = 0;
        while (vpu.execute()) {
            i++;
        }

        // sum of pre-loaded & then-completed steps is always 8.
        Assert.assertEquals(8, i + states.indexOf(state));
    }
}

From source file:org.nekorp.workflow.desktop.control.imp.WorkflowAppPrototipo.java

@Override
public void guardaServicio() {
    try {//from w ww.ja va  2s .  co  m
        if (!validacionGeneralCliente.isValido()) {
            mensajesControl.reportaError("Los datos del cliente contienen errores.");
            throw new IllegalArgumentException();
        }
        if (!validacionGeneralDatosAuto.isValido()) {
            mensajesControl.reportaError("Los datos del auto contienen errores.");
            throw new IllegalArgumentException();
        }
        Servicio servicio = new Servicio();
        servicioBridge.unload(servicioVB, servicio);

        //TODO implementar una version que si sirva del editor monitor para ver que esta editado
        //y guardar unicamente lo que se haya editado
        //se guardan los datos del cliente.
        ClienteMxPojo cliente = new ClienteMxPojo();
        customerBridge.unload(servicioVB.getCliente(), cliente);
        customerDAO.guardar(cliente);
        //se vuelve a cargar el cliente
        customerBridge.load(cliente, servicioVB.getCliente());
        //se actualiza el id del cliente en el servicio
        servicio.setIdCliente(cliente.getId());
        //se guardan los datos del auto,
        Auto auto = new Auto();
        autoBridge.unload(servicioVB.getAuto(), auto);
        autoDAO.guardar(auto);
        //se vuelve a cargar el auto
        autoBridge.load(auto, servicioVB.getAuto());
        //se actualiza el id del auto en el servicio
        servicio.setIdAuto(auto.getNumeroSerie());
        //se guarda el servicio
        servicioDAO.guardar(servicio);

        //en teoria solo habria que guardar los que se editaron
        //pero en la opcion de guardar individual
        List<Evento> bitacora = new LinkedList<>();
        bitacoraBridge.unload(servicioVB.getBitacora(), bitacora);
        //el servicio regresa los registros de la bitacora con id
        bitacora = bitacoraDAO.guardar(servicio.getId(), bitacora);
        //se vuelven a cargar los eventos pero ahora con id.
        bitacoraBridge.load(bitacora, servicioVB.getBitacora());
        //los costos
        List<RegistroCosto> costo = new LinkedList<>();
        costoBridge.unload(servicioVB.getCostos(), costo);
        //el servicio regresa los registros de costo con id
        costo = costoDAO.guardar(servicio.getId(), costo);
        //se cargan los costos de nuevo
        List<RegistroCostoVB> costoVB = new LinkedList<>();
        costoBridge.load(costo, costoVB);
        Collections.sort(costoVB);
        servicioVB.setCostos(costoVB);
        // inventario de daos
        List<DamageDetail> damage = new LinkedList<>();
        inventarioDamageBridge.unload(servicioVB.getDatosAuto().getDamage(), damage);
        damage = inventarioDamageDAO.guardar(servicio.getId(), damage);
        //se vuelven a cargar pero ahora con id.
        inventarioDamageBridge.load(damage, servicioVB.getDatosAuto().getDamage());
        //se carga de nuevo el servicio para tener el metadata
        servicio = servicioDAO.cargar(servicio.getId());
        servicioBridge.load(servicio, servicioVB);
        boolean eraNuevo = edicionMetadata.getServicioActual().isNuevo();
        ServicioLoaded servicioLoaded = edicionMetadata.getServicioActual();
        servicioLoaded.setAuto(auto);
        servicioLoaded.setBitacora(bitacora);
        servicioLoaded.setCliente(cliente);
        servicioLoaded.setCosto(costo);
        servicioLoaded.setDamage(damage);
        servicioLoaded.setServicio(servicio);
        if (eraNuevo) {
            List<ServicioLoaded> nuevos = servicioLoadedListMetadata.getServiciosNuevos();
            nuevos.remove(edicionMetadata.getServicioActual());
            servicioLoadedListMetadata.setServiciosNuevos(nuevos);
            List<ServicioLoaded> servicios = servicioLoadedListMetadata.getServicios();
            servicios.add(servicioLoaded);
            servicioLoadedListMetadata.setServicios(servicios);
        } else {
            List<ServicioLoaded> servicios = servicioLoadedListMetadata.getServicios();
            int index = servicios.indexOf(edicionMetadata.getServicioActual());
            servicios.add(index, servicioLoaded);
            servicios.remove(edicionMetadata.getServicioActual());
            servicioLoadedListMetadata.setServicios(servicios);
        }
        edicionMetadata.setServicioActual(servicioLoaded);
    } catch (ResourceAccessException e) {
        WorkflowAppPrototipo.LOGGER.error("error al guardar un servicio" + e.getMessage());
        this.mensajesControl.reportaError("Error de comunicacion con el servidor");
    }
}

From source file:fr.obeo.emf.specimen.SpecimenGenerator.java

private void createResource(ResourceSet resourceSet, Map<EClass, Integer> resourcesSize,
        TreeIterator<EObject> eAllContents, EObject eObject, List<EObject> ret) {
    TreeIterator<EObject> properContents = EcoreUtil.getAllProperContents(eObject, true);
    int allProperContentsSize = Iterators.size(properContents);
    EClass eClass = eObject.eClass();/*from w  w  w  . j  a  v a2 s .  co  m*/
    Integer integer = resourcesSize.get(eClass);
    if (integer != null && allProperContentsSize <= integer.intValue()) {
        createResource(resourceSet, eObject);
        setNextResourceSizeForType(resourcesSize, eClass);
        eAllContents.prune();
    } else if (eObject.eContainer() == null) {
        List<EObject> precedingSibling = ret.subList(0, ret.indexOf(eObject));
        TreeIterator<Object> allPrecedingSiblingContents = EcoreUtil.getAllProperContents(precedingSibling,
                true);
        int allPrecedingSiblingContentsSize = Iterators.size(allPrecedingSiblingContents);
        if (integer != null && allPrecedingSiblingContentsSize >= integer.intValue()) {
            createResource(resourceSet, eObject);
            setNextResourceSizeForType(resourcesSize, eClass);
            eAllContents.prune();
        }
    }
}

From source file:au.com.ish.derbydump.derbydump.main.DumpTest.java

@Test
public void theDumpTest() throws Exception {
    // Create table
    StringBuilder createTableBuffer = new StringBuilder();
    createTableBuffer.append("CREATE TABLE ");
    createTableBuffer.append(Configuration.getConfiguration().getSchemaName());
    createTableBuffer.append(".");
    createTableBuffer.append(tableName);
    createTableBuffer.append(" (");

    StringBuilder insertBuffer = new StringBuilder();
    insertBuffer.append("INSERT INTO ");
    insertBuffer.append(RESOURCE_SCHEMA_NAME);
    insertBuffer.append(".");
    insertBuffer.append(tableName);/*from  ww w  . j  a v  a  2 s  .  c om*/
    insertBuffer.append(" VALUES (");

    for (String col : columns) {
        createTableBuffer.append(col.toUpperCase());
        //String[] c = col.split(" ");
        //insertBuffer.append(c[0].toUpperCase().trim());
        insertBuffer.append("?");
        if (!columns[columns.length - 1].equals(col)) {
            createTableBuffer.append(", ");
            insertBuffer.append(",");
        }
    }

    createTableBuffer.append(")");
    insertBuffer.append(")");

    config.setTableRewriteProperty("testSkip", "--exclude--");
    config.setTableRewriteProperty("testRename", "testRenameNew");
    config.setTruncateTables(truncate);

    File f = new File("./build/outputs/" + tableName + ".sql");
    if (f.exists()) {
        f.delete();
    }
    f.mkdirs();

    config.setOutputFilePath(f.getCanonicalPath());

    Connection connection = db.createNewConnection();
    Statement statement = connection.createStatement();
    PreparedStatement ps = null;

    try {
        statement.execute(createTableBuffer.toString());
        connection.commit();
        //config.setTableRewriteProperty("TABLE2", "--exclude--");

        for (Object o : valuesToInsert) {
            Object[] vals = (Object[]) o;
            if (vals.length > 0) {
                ps = db.getConnection().prepareStatement(insertBuffer.toString());
                for (int i = 0; i < vals.length; i++) {
                    if (vals[i] instanceof InputStream) {
                        ps.setBinaryStream(i + 1, (InputStream) vals[i]);
                    } else {
                        ps.setObject(i + 1, vals[i]);
                    }
                }
                ps.execute();
                connection.commit();
            }
        }

        OutputThread output = new OutputThread();
        Thread writer = new Thread(output, "File_Writer");
        writer.start();

        new DatabaseReader(output);
        // Let the writer know that no more data is coming
        writer.interrupt();
        writer.join();

        // Now let's read the output and see what is in it
        List<String> lines = FileUtils.readLines(f);

        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 0;", lines.get(0));
        assertEquals("Missing foreign key operations", "SET FOREIGN_KEY_CHECKS = 1;",
                lines.get(lines.size() - 1));

        if (!skipped) {
            assertTrue("LOCK missing", lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
            assertTrue("UNLOCK missing", lines.contains("UNLOCK TABLES;"));

            int index = lines.indexOf("LOCK TABLES `" + outputTableName + "` WRITE;");

            if (truncate) {
                assertTrue("TRUNCATE missing", lines.contains("TRUNCATE TABLE " + outputTableName + ";"));
                assertTrue("INSERT missing, got " + lines.get(index + 2),
                        lines.get(index + 2).startsWith("INSERT INTO " + outputTableName));
            } else {
                assertTrue("INSERT missing, got " + lines.get(index + 1),
                        lines.get(index + 1).startsWith("INSERT INTO " + outputTableName));
            }

            for (String s : validOutputs) {
                assertTrue("VALUES missing :" + s, lines.contains(s));
            }
        } else {
            assertTrue("LOCK missing", !lines.contains("LOCK TABLES `" + outputTableName + "` WRITE;"));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("failed to create test data" + e.getMessage());
    } finally {
        if (ps != null) {
            ps.close();
        }
        statement.close();
        connection.close();
    }
}

From source file:com.amalto.workbench.editors.DataClusterComposite.java

/**
 * this method will be call when search action is activated or page is changed every time
 *///from  w  w w.  j a  va2s  .  co m
private void doSearchSort() {
    Table table = resultsViewer.getTable();
    TableColumn sortColumn = table.getSortColumn();
    if (sortColumn != null) {
        List<TableColumn> columns = Arrays.asList(table.getColumns());
        int index = columns.indexOf(sortColumn);
        sort(index, sortColumn);
    }
}

From source file:com.edmunds.zookeeper.election.ZooKeeperElection.java

/**
 * Performs the check to confirm (absolutely that we are the master).
 *//* w ww  . java2 s .  c o m*/
void processResultRootChildren(int rc, String path, ZooKeeperElectionContext ctx, List<String> children) {
    if (rc != 0) {
        error("Failed to list children of root node", rc, path, ctx);
        return;
    }

    if (!checkActive(ctx)) {
        return;
    }

    cleanupPriorExecution(ctx, path, children);

    final String memberName = ctx.getName();

    // Make sure all the children are sorted by time
    Collections.sort(children, SEQUENTIAL_COMPARATOR);

    final int memberIndex = children.indexOf(memberName);

    ctx.setMaster(memberIndex == 0);

    if (memberIndex == -1) {
        // Since we just added it our node should be present!!
        error("Election node not found: " + memberName, Code.NONODE, path, ctx);
        return;
    }

    if (memberIndex > 0) {
        final String previousName = children.get(memberIndex - 1);
        final String previousPath = rootPath + "/" + previousName;

        if (logger.isInfoEnabled()) {
            logger.info(String.format("Waiting for previous node: %s, Current Index: %d", previousName,
                    memberIndex));
        }

        // Wait for the previous node to be deleted.
        // Using getData() instead of exists() because I don't want a NodeCreated event.
        connection.getData(previousPath, ctx.createWatcher(callbackPreviousWatcher), callbackPreviousData, ctx);
    }

    connection.getData(ctx.getPath(), ctx.createWatcher(callbackCurrentWatcher), callbackCurrentData, ctx);
}

From source file:au.gov.ansto.bragg.kakadu.ui.plot.MultiPlotDataManager.java

public void removePlotDataItem(PlotDataItem plotDataItem) {

    setLinked(plotDataItem, false);//from  w  ww.ja v a2  s .  c  om
    plotDataItems.remove(plotDataItem.getId());
    PlotType type = plot.getCurrentPlotType();
    switch (type) {
    case OffsetPlot:
    case OverlayPlot:
        IXYErrorDataset dataset1D = (IXYErrorDataset) plot.getCurrentPlotWidget().getDataset();
        List<IXYErrorSeries> seriesList = dataset1D.getSeries();
        for (IXYErrorSeries series : seriesList) {
            if (series == plotDataItem.getPlotData()) {
                int seriesIndex = seriesList.indexOf(series);
                dataset1D.removeSeries(series);
                XYItemRenderer renderer = plot.getCurrentPlotWidget().getXYPlot().getRenderer();
                if (renderer instanceof AbstractRenderer) {
                    ((AbstractRenderer) renderer).removeSeries(seriesIndex);
                }
            }
        }
        break;
    case IntensityPlot:
        IGroup group = plotDataItem.getData();
        Hist2DDataset dataset2D = (Hist2DDataset) plot.getCurrentPlotWidget().getDataset();
        if (group.getShortName().equals(dataset2D.getTitle())) {
            plot.getCurrentPlotWidget().setDataset(new Hist2DDataset());
        }
        break;
    default:
        break;
    }
    try {
        plot.getCurrentPlotWidget().updatePlot();
    } catch (Exception e) {
        plot.handleException(e);
    }
    fireItemRemovedEvent(plotDataItem);

    for (PlotDataItem pItem : plotDataItem.getChildren()) {
        removePlotDataItem(pItem);
    }
}

From source file:org.ambraproject.article.service.BrowseServiceImpl.java

/**
 * Get Issue information./*from  w w w . j a  va2 s  . co  m*/
 *
 * @param issueDoi DOI of Issue.
 * @return the Issue information.
 */
@Transactional(readOnly = true)
public IssueInfo getIssueInfo(final URI issueDoi) {
    return (IssueInfo) hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            // get the Issue
            final Issue issue = (Issue) hibernateTemplate.get(Issue.class, issueDoi);
            if (issue == null) {
                log.error("Failed to retrieve Issue for doi='" + issueDoi.toString() + "'");
                return null;
            }

            // get the image Article
            URI imageArticle = null;
            String description = issue.getDescription();
            if ((issue.getImage() != null) && (issue.getImage().toString().length() != 0)) {
                imageArticle = issue.getImage();
            }

            // derive prev/next Issue, "parent" Volume
            URI prevIssueURI = null;
            URI nextIssueURI = null;
            Volume parentVolume = null;

            List<String> results = session
                    .createSQLQuery("select aggregationUri from VolumeIssueList where issueUri = :doi")
                    .setParameter("doi", issueDoi.toString()).list();
            if (results.size() > 0) {
                URI volumeURI = URI.create(results.get(0));
                parentVolume = (Volume) session.load(Volume.class, volumeURI);
            }
            if (parentVolume != null) {
                final List<URI> issues = parentVolume.getIssueList();
                final int issuePos = issues.indexOf(issueDoi);
                prevIssueURI = (issuePos == 0) ? null : issues.get(issuePos - 1);
                nextIssueURI = (issuePos == issues.size() - 1) ? null : issues.get(issuePos + 1);
            } else {
                log.warn("Issue: " + issue.getId() + ", not contained in any Volumes");
            }

            IssueInfo issueInfo = new IssueInfo(issue.getId(), issue.getDisplayName(), prevIssueURI,
                    nextIssueURI, imageArticle, description,
                    parentVolume == null ? null : parentVolume.getId());
            issueInfo.setArticleUriList(getArticleList(issue));
            return issueInfo;

        }
    });
}

From source file:com.thoughtworks.go.config.JobConfig.java

public void encryptSecureProperties(CruiseConfig preprocessedConfig, PipelineConfig preprocessedPipelineConfig,
        JobConfig preprocessedJobConfig) {
    List<PluggableArtifactConfig> artifactConfigs = artifactConfigs().getPluggableArtifactConfigs();
    List<PluggableArtifactConfig> preprocessedArtifactConfigs = preprocessedJobConfig.artifactConfigs()
            .getPluggableArtifactConfigs();
    artifactConfigs.forEach(artifactConfig -> {
        artifactConfig.encryptSecureProperties(preprocessedConfig,
                preprocessedArtifactConfigs.get(artifactConfigs.indexOf(artifactConfig)));
    });/*from w  ww  . j  ava2  s  .  c  o  m*/

    tasks.forEach(task -> {
        if (task instanceof FetchPluggableArtifactTask) {
            ((FetchPluggableArtifactTask) task).encryptSecureProperties(preprocessedConfig,
                    preprocessedPipelineConfig,
                    (FetchPluggableArtifactTask) preprocessedJobConfig.getTasks().get(tasks.indexOf(task)));
        }
    });
}

From source file:net.sourceforge.subsonic.ajax.PlayQueueService.java

public PlayQueueInfo play(int id) throws Exception {
    HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
    HttpServletResponse response = WebContextFactory.get().getHttpServletResponse();

    Player player = getCurrentPlayer(request, response);
    MediaFile file = mediaFileService.getMediaFile(id);

    if (file.isFile()) {
        String username = securityService.getCurrentUsername(request);
        boolean queueFollowingSongs = settingsService.getUserSettings(username).isQueueFollowingSongs();
        List<MediaFile> songs;
        if (queueFollowingSongs) {
            MediaFile dir = mediaFileService.getParentOf(file);
            songs = mediaFileService.getChildrenOf(dir, true, false, true);
            if (!songs.isEmpty()) {
                int index = songs.indexOf(file);
                songs = songs.subList(index, songs.size());
            }/*w  w w.  j  av  a2  s . c o  m*/
        } else {
            songs = Arrays.asList(file);
        }
        return doPlay(request, player, songs).setStartPlayerAt(0);
    } else {
        List<MediaFile> songs = mediaFileService.getDescendantsOf(file, true);
        return doPlay(request, player, songs).setStartPlayerAt(0);
    }
}