Example usage for java.util ListIterator hasPrevious

List of usage examples for java.util ListIterator hasPrevious

Introduction

In this page you can find the example usage for java.util ListIterator hasPrevious.

Prototype

boolean hasPrevious();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the reverse direction.

Usage

From source file:hws.core.ExecutorThread.java

public void run() {
    Logger.info("Starting stream processing pipeline");
    for (DefaultExecutor defaultExecutor : this.startingOrder) {
        try {/*w  ww  .  ja va2 s . co  m*/
            defaultExecutor.start();
        } catch (Exception e) {
            Logger.severe(e.toString());
        }
    }
    Logger.info("Finishing stream processing pipeline");
    ListIterator<DefaultExecutor> li = this.startingOrder.listIterator(this.startingOrder.size());
    while (li.hasPrevious()) {
        DefaultExecutor defaultExecutor = li.previous();
        try {
            defaultExecutor.finish();
        } catch (Exception e) {
            Logger.severe(e.toString());
        }
    }
    //zk.createPersistent(finishZnode, "");
    Logger.info("Latch Counting Down.");
    this.latch.countDown();
    Logger.info("End of ExecutorThread");
    //this.executor.start();
    //this.executor.finish();

}

From source file:org.eclipse.jubula.client.core.utils.RefToken.java

/**
 * gets the real value for a reference//from  ww  w.j  a  v  a  2s .co  m
 * @param stack current execution stack
 * @param locale currently used locale for testexecution
 * @return the real value for this reference token and given dataset number
 * @throws InvalidDataException if given reference is not resolvable
 */
public String getExecutionString(List<ExecObject> stack, Locale locale) throws InvalidDataException {
    String refGuid = extractCore(getModelString());
    ListIterator<ExecObject> it = stack.listIterator(stack.size());
    while (it.hasPrevious()) {
        ExecObject obj = it.previous();
        String parameterValue = obj.getParameterValue(refGuid);
        if (parameterValue != null) {
            return parameterValue;
        }
    }
    throwInvalidDataException(extractCore(getGuiString()));
    return null;
}

From source file:de.innovationgate.webgate.api.templates.LazyBeanList.java

public int lastIndexOf(Object arg0) {
    ListIterator keys = _keys.listIterator();
    Object key;/*  w ww.  ja  v a 2s. com*/
    Object bean;
    while (keys.hasPrevious()) {
        key = keys.previous();
        try {
            bean = fetch(key);
        } catch (WGAPIException e) {
            throw new IllegalStateException("Unable to execute internal fetch() bc. of exception: "
                    + e.getClass().getName() + " message: " + e.getMessage());
        }
        if (bean.equals(arg0)) {
            return _keys.indexOf(key);
        }
    }
    return -1;
}

From source file:com.redhat.lightblue.query.Projection.java

private Inclusion getFieldInclusion(Path field, ProjectionList p, Path context) {
    LOGGER.debug("Checking if a projection list projects {}", field);
    Inclusion lastResult = Inclusion.undecided;
    List<Projection> items = p.getItems();
    ListIterator<Projection> itemsItr = items.listIterator(items.size());
    while (itemsItr.hasPrevious()) {
        Inclusion ret = itemsItr.previous().getFieldInclusion(field, context);
        if (ret != Inclusion.undecided) {
            lastResult = ret;//w  w w  .j  ava  2s .c o m
            break;
        }
    }
    LOGGER.debug("Projection list projects {}: {}", field, lastResult);
    return lastResult;
}

From source file:jp.aegif.nemaki.tracker.CoreTracker.java

/**
 *
 * @param events/*from  w w w.  j a v  a2s . c  o m*/
 * @return
 */
private List<ChangeEvent> extractChangeEvent(List<ChangeEvent> events) {
    List<ChangeEvent> list = new ArrayList<ChangeEvent>();
    Set<String> objectIds = new HashSet<String>();

    int size = events.size();
    ListIterator<ChangeEvent> iterator = events.listIterator(size);
    while (iterator.hasPrevious()) {
        ChangeEvent event = iterator.previous();
        if (objectIds.contains(event.getObjectId())) {
            continue;
        } else {
            objectIds.add(event.getObjectId());
            list.add(event);
        }
    }

    Collections.reverse(list);
    return list;
}

From source file:org.xchain.framework.lifecycle.Lifecycle.java

/**
 * Start all lifecycle steps found by the LifecycleStepScanner.
 * //  w  w w. j av a 2 s .  c  o  m
 * @throws LifecycleException If an exception was encountered attempting to start the lifecycle steps.
 * @see LifecycleStepScanner
 */
private static void startLifecycleSteps() throws LifecycleException {
    // Create a scanner to find the lifecycle steps in the current classpath.
    LifecycleStepScanner scanner = new LifecycleStepScanner(context);
    try {
        scanner.scan();
        lifecycleStepList = scanner.getLifecycleStepList();
    } catch (ScanException se) {
        throw new LifecycleException("An exception was thrown while scanning for lifecycle steps.", se);
    }

    if (log.isInfoEnabled()) {
        StringBuilder message = new StringBuilder();
        message.append("Found ").append(lifecycleStepList.size()).append(" lifecycle steps:\n");
        for (LifecycleStep lifecycleStep : lifecycleStepList) {
            message.append("  ").append(lifecycleStep.getQName()).append("\n");
        }
        log.info(message.toString());
    }

    // Start all the found lifecycle steps.
    ListIterator<LifecycleStep> iterator = lifecycleStepList.listIterator();
    try {
        while (iterator.hasNext()) {
            LifecycleStep lifecycleStep = iterator.next();

            if (log.isInfoEnabled()) {
                log.info("Starting Lifecycle Step '" + lifecycleStep.getQName() + "'.");
            }
            lifecycleStep.startLifecycle(context, Lifecycle.configDocumentContext);
            if (log.isInfoEnabled()) {
                log.info("Finished Lifecycle Step '" + lifecycleStep.getQName() + "'.");
            }
        }
    } catch (LifecycleException le) {
        if (log.isErrorEnabled()) {
            log.error("Stopping the lifecycle startup due to a lifecycle exception.", le);
        }
        iterator.previous();
        while (iterator.hasPrevious()) {
            LifecycleStep lifecycleStep = iterator.previous();
            try {
                lifecycleStep.stopLifecycle(context);
            } catch (Throwable t) {
                if (log.isWarnEnabled()) {
                    log.warn("An exception was thrown while stopping a lifecycle exception.", t);
                }
            }
        }

        // clear the lifecycle step list.
        lifecycleStepList.clear();

        // we should throw the lifecycle exception here.
        throw le;
    } finally {
        // make sure the configuration DOM gets garbage collected, no reason to keep it around once everyone is configured.
        Lifecycle.configDocumentContext = null;
    }

}

From source file:org.apache.storm.metricstore.rocksdb.RocksDbMetricsWriter.java

/**
 * Performs the actual metric insert, and aggregates over all bucket times.
 *
 * @param metric  Metric to store//  ww w .  j ava  2  s  .c o  m
 * @throws MetricException  if database write fails
 */
private void processInsert(Metric metric) throws MetricException {

    // convert all strings to numeric Ids for the metric key and add to the metadata cache
    long metricTimestamp = metric.getTimestamp();
    Integer topologyId = storeMetadataString(KeyType.TOPOLOGY_STRING, metric.getTopologyId(), metricTimestamp);
    Integer metricId = storeMetadataString(KeyType.METRIC_STRING, metric.getMetricName(), metricTimestamp);
    Integer componentId = storeMetadataString(KeyType.COMPONENT_STRING, metric.getComponentId(),
            metricTimestamp);
    Integer executorId = storeMetadataString(KeyType.EXEC_ID_STRING, metric.getExecutorId(), metricTimestamp);
    Integer hostId = storeMetadataString(KeyType.HOST_STRING, metric.getHostname(), metricTimestamp);
    Integer streamId = storeMetadataString(KeyType.STREAM_ID_STRING, metric.getStreamId(), metricTimestamp);

    RocksDbKey key = RocksDbKey.createMetricKey(AggLevel.AGG_LEVEL_NONE, topologyId, metric.getTimestamp(),
            metricId, componentId, executorId, hostId, metric.getPort(), streamId);

    // save metric key/value to be batched
    RocksDbValue value = new RocksDbValue(metric);
    insertBatch.put(key, value);

    // Aggregate matching metrics over bucket timeframes.
    // We'll process starting with the longest bucket.  If the metric for this does not exist, we don't have to
    // search for the remaining bucket metrics.
    ListIterator li = aggBuckets.listIterator(aggBuckets.size());
    boolean populate = true;
    while (li.hasPrevious()) {
        AggLevel bucket = (AggLevel) li.previous();
        Metric aggMetric = new Metric(metric);
        aggMetric.setAggLevel(bucket);

        long msToBucket = 1000L * 60L * bucket.getValue();
        long roundedToBucket = msToBucket * (metric.getTimestamp() / msToBucket);
        aggMetric.setTimestamp(roundedToBucket);

        RocksDbKey aggKey = RocksDbKey.createMetricKey(bucket, topologyId, aggMetric.getTimestamp(), metricId,
                componentId, executorId, hostId, aggMetric.getPort(), streamId);

        if (populate) {
            // retrieve any existing aggregation matching this one and update the values
            if (store.populateFromKey(aggKey, aggMetric)) {
                aggMetric.addValue(metric.getValue());
            } else {
                // aggregating metric did not exist, don't look for further ones with smaller timestamps
                populate = false;
            }
        }

        // save metric key/value to be batched
        RocksDbValue aggVal = new RocksDbValue(aggMetric);
        insertBatch.put(aggKey, aggVal);
    }

    processBatchInsert(insertBatch);

    insertBatch.clear();
}

From source file:com.google.gwt.emultest.java.util.ListTestBase.java

public void testListIteratorHasNextHasPreviousAndIndexes() {
    List l = makeEmptyList();/*from w w w. j  a v a 2s  . c o m*/
    ListIterator i = l.listIterator();
    assertFalse(i.hasNext());
    assertFalse(i.hasPrevious());
    i.add(new Integer(1));
    assertEquals(1, i.nextIndex());
    assertEquals(0, i.previousIndex());
    i = l.listIterator();
    assertEquals(0, i.nextIndex());
    assertEquals(-1, i.previousIndex());
    assertTrue(i.hasNext());
    assertFalse(i.hasPrevious());
    i.next();
    assertEquals(1, i.nextIndex());
    assertEquals(0, i.previousIndex());
    assertFalse(i.hasNext());
    assertTrue(i.hasPrevious());
}

From source file:org.apache.atlas.model.typedef.AtlasEnumDef.java

public void setElementDefs(List<AtlasEnumElementDef> elementDefs) {
    if (elementDefs != null && this.elementDefs == elementDefs) {
        return;/*from w  ww.  j ava  2s.c om*/
    }

    if (CollectionUtils.isEmpty(elementDefs)) {
        this.elementDefs = new ArrayList<>();
    } else {
        // if multiple elements with same value are present, keep only the last entry
        List<AtlasEnumElementDef> tmpList = new ArrayList<>(elementDefs.size());
        Set<String> elementValues = new HashSet<>();

        ListIterator<AtlasEnumElementDef> iter = elementDefs.listIterator(elementDefs.size());
        while (iter.hasPrevious()) {
            AtlasEnumElementDef elementDef = iter.previous();
            String elementValue = elementDef != null ? elementDef.getValue() : null;

            if (elementValue != null) {
                elementValue = elementValue.toLowerCase();

                if (!elementValues.contains(elementValue)) {
                    tmpList.add(new AtlasEnumElementDef(elementDef));

                    elementValues.add(elementValue);
                }
            }
        }
        Collections.reverse(tmpList);

        this.elementDefs = tmpList;
    }
}

From source file:samples.com.axiomine.largecollections.util.KryoListSample.java

public static void workOnKryoList(KryoList<Integer> lst) {
    try {//from  w  w w.  j a v a 2s  . com
        ListIterator<Integer> it = lst.listIterator();

        for (int i = 0; i < 10; i++) {
            boolean b = lst.add(i);
            Assert.assertEquals(true, true);
        }
        System.out.println("Size of map=" + lst.size());
        System.out.println("Value for key 0=" + lst.get(0));
        ;
        System.out.println("Now remove key 0");
        try {
            int i = lst.remove(0);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        int i = lst.remove(9);
        System.out.println("Value for deleted key=" + i);
        ;
        System.out.println("Size of map=" + lst.size());

        lst.close();
        boolean b = false;
        try {
            lst.add(9);
        } catch (Exception ex) {
            System.out.println("Exception because acces after close");
            b = true;
        }
        lst.open();
        System.out.println("Open again");
        b = lst.add(9);

        Assert.assertEquals(true, b);
        i = lst.set(9, 99);
        Assert.assertEquals(99, i);
        i = lst.set(5, 55);
        Assert.assertEquals(55, i);
        i = lst.set(0, 100);
        Assert.assertEquals(100, i);
        System.out.println(lst.get(0));
        System.out.println(lst.get(5));
        System.out.println(lst.get(9));
        System.out.println("Now put worked. Size of map should be 10. Size of the map =" + lst.size());

        Iterator<Integer> iter = lst.iterator();
        try {
            while (iter.hasNext()) {
                i = iter.next();
                System.out.println("From ITerator = " + i);
            }
        } finally {
            //Always close and iterator after use. Otherwise you will not be able to call the clear function
            ((Closeable) iter).close();
        }

        ListIterator<Integer> lstIter = lst.listIterator();
        try {
            while (lstIter.hasNext()) {
                i = lstIter.next();
                System.out.println("From List Iterator = " + i);
                System.out.println("From List Iterator Next Index= " + lstIter.nextIndex());
            }
        } finally {
            //Always close and iterator after use. Otherwise you will not be able to call the clear function
            ((Closeable) lstIter).close();
        }

        lstIter = lst.listIterator(5);
        try {
            while (lstIter.hasNext()) {
                i = lstIter.next();
                System.out.println("From List Iterator = " + i);
                System.out.println("From List Iterator Next Index= " + lstIter.nextIndex());
            }
        } finally {
            //Always close and iterator after use. Otherwise you will not be able to call the clear function
            ((Closeable) lstIter).close();
        }

        System.out.println("---");
        lstIter = lst.listIterator(9);
        try {
            while (lstIter.hasPrevious()) {
                i = lstIter.previous();
                System.out.println("From List Iterator Previous= " + i);
                System.out.println("From List Iterator Previous Index= " + lstIter.previousIndex());
            }
        } finally {
            //Always close and iterator after use. Otherwise you will not be able to call the clear function
            ((Closeable) lstIter).close();
        }

        System.out.println("----------------------------------");
        lstIter = lst.listIterator();
        try {
            while (lstIter.hasNext()) {
                i = lstIter.next();
                System.out.println("Iterating Forward = " + i);
            }

        } finally {
            //Always close and iterator after use. Otherwise you will not be able to call the clear function
            ((Closeable) lstIter).close();
        }

        System.out.println("Now Serialize the List");
        File serFile = new File(System.getProperty("java.io.tmpdir") + "/x.ser");
        FileSerDeUtils.serializeToFile(lst, serFile);
        System.out.println("Now De-Serialize the List");
        lst = (KryoList<Integer>) FileSerDeUtils.deserializeFromFile(serFile);
        System.out.println("After De-Serialization " + lst);
        System.out.println("After De-Serialization Size of map should be 10. Size of the map =" + lst.size());
        printListCharacteristics(lst);
        System.out.println("Now calling lst.clear()");
        lst.clear();
        System.out.println("After clear list size should be 0 and =" + lst.size());
        lst.add(0);
        System.out.println("Just added a record and lst size =" + lst.size());
        System.out.println("Finally Destroying");
        lst.destroy();

        System.out.println("Cleanup serialized file");
        FileUtils.deleteQuietly(serFile);

    } catch (Exception ex) {
        throw Throwables.propagate(ex);
    }

}