Search in sources :

Example 1 with NoSuchElementException

use of java.util.NoSuchElementException in project jetty.project by eclipse.

the class ByteBufferContentProvider method iterator.

@Override
public Iterator<ByteBuffer> iterator() {
    return new Iterator<ByteBuffer>() {

        private int index;

        @Override
        public boolean hasNext() {
            return index < buffers.length;
        }

        @Override
        public ByteBuffer next() {
            try {
                ByteBuffer buffer = buffers[index];
                buffers[index] = buffer.slice();
                ++index;
                return buffer;
            } catch (ArrayIndexOutOfBoundsException x) {
                throw new NoSuchElementException();
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
Also used : Iterator(java.util.Iterator) ByteBuffer(java.nio.ByteBuffer) NoSuchElementException(java.util.NoSuchElementException)

Example 2 with NoSuchElementException

use of java.util.NoSuchElementException in project jetty.project by eclipse.

the class InputStreamContentProviderTest method testStreamWithContentThenNextThenNext.

@Test
public void testStreamWithContentThenNextThenNext() {
    final AtomicBoolean closed = new AtomicBoolean();
    ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] { 1 }) {

        @Override
        public void close() throws IOException {
            super.close();
            closed.compareAndSet(false, true);
        }
    };
    InputStreamContentProvider provider = new InputStreamContentProvider(stream);
    Iterator<ByteBuffer> iterator = provider.iterator();
    Assert.assertNotNull(iterator);
    ByteBuffer buffer = iterator.next();
    Assert.assertNotNull(buffer);
    try {
        iterator.next();
        Assert.fail();
    } catch (NoSuchElementException expected) {
    }
    Assert.assertFalse(iterator.hasNext());
    Assert.assertTrue(closed.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteBuffer(java.nio.ByteBuffer) NoSuchElementException(java.util.NoSuchElementException) Test(org.junit.Test)

Example 3 with NoSuchElementException

use of java.util.NoSuchElementException in project druid by druid-io.

the class QueryableIndexIndexableAdapter method getRows.

@Override
public Iterable<Rowboat> getRows() {
    return new Iterable<Rowboat>() {

        @Override
        public Iterator<Rowboat> iterator() {
            return new Iterator<Rowboat>() {

                final GenericColumn timestamps = input.getColumn(Column.TIME_COLUMN_NAME).getGenericColumn();

                final Closeable[] metrics;

                final Closeable[] columns;

                final Closer closer = Closer.create();

                final int numMetrics = getMetricNames().size();

                final DimensionHandler[] handlers = new DimensionHandler[availableDimensions.size()];

                Collection<DimensionHandler> handlerSet = input.getDimensionHandlers().values();

                int currRow = 0;

                boolean done = false;

                {
                    closer.register(timestamps);
                    handlerSet.toArray(handlers);
                    this.columns = FluentIterable.from(handlerSet).transform(new Function<DimensionHandler, Closeable>() {

                        @Override
                        public Closeable apply(DimensionHandler handler) {
                            Column column = input.getColumn(handler.getDimensionName());
                            return handler.getSubColumn(column);
                        }
                    }).toArray(Closeable.class);
                    for (Closeable column : columns) {
                        closer.register(column);
                    }
                    final Indexed<String> availableMetrics = getMetricNames();
                    metrics = new Closeable[availableMetrics.size()];
                    for (int i = 0; i < metrics.length; ++i) {
                        final Column column = input.getColumn(availableMetrics.get(i));
                        final ValueType type = column.getCapabilities().getType();
                        switch(type) {
                            case FLOAT:
                            case LONG:
                                metrics[i] = column.getGenericColumn();
                                break;
                            case COMPLEX:
                                metrics[i] = column.getComplexColumn();
                                break;
                            default:
                                throw new ISE("Cannot handle type[%s]", type);
                        }
                    }
                    for (Closeable metricColumn : metrics) {
                        closer.register(metricColumn);
                    }
                }

                @Override
                public boolean hasNext() {
                    final boolean hasNext = currRow < numRows;
                    if (!hasNext && !done) {
                        CloseQuietly.close(closer);
                        done = true;
                    }
                    return hasNext;
                }

                @Override
                public Rowboat next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException();
                    }
                    final Object[] dims = new Object[columns.length];
                    int dimIndex = 0;
                    for (final Closeable column : columns) {
                        dims[dimIndex] = handlers[dimIndex].getEncodedKeyComponentFromColumn(column, currRow);
                        dimIndex++;
                    }
                    Object[] metricArray = new Object[numMetrics];
                    for (int i = 0; i < metricArray.length; ++i) {
                        if (metrics[i] instanceof IndexedFloatsGenericColumn) {
                            metricArray[i] = ((GenericColumn) metrics[i]).getFloatSingleValueRow(currRow);
                        } else if (metrics[i] instanceof IndexedLongsGenericColumn) {
                            metricArray[i] = ((GenericColumn) metrics[i]).getLongSingleValueRow(currRow);
                        } else if (metrics[i] instanceof ComplexColumn) {
                            metricArray[i] = ((ComplexColumn) metrics[i]).getRowValue(currRow);
                        }
                    }
                    final Rowboat retVal = new Rowboat(timestamps.getLongSingleValueRow(currRow), dims, metricArray, currRow, handlers);
                    ++currRow;
                    return retVal;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };
}
Also used : Closer(com.google.common.io.Closer) IndexedLongsGenericColumn(io.druid.segment.column.IndexedLongsGenericColumn) GenericColumn(io.druid.segment.column.GenericColumn) IndexedFloatsGenericColumn(io.druid.segment.column.IndexedFloatsGenericColumn) IndexedIterable(io.druid.segment.data.IndexedIterable) FluentIterable(com.google.common.collect.FluentIterable) ValueType(io.druid.segment.column.ValueType) Closeable(java.io.Closeable) IndexedLongsGenericColumn(io.druid.segment.column.IndexedLongsGenericColumn) IndexedLongsGenericColumn(io.druid.segment.column.IndexedLongsGenericColumn) GenericColumn(io.druid.segment.column.GenericColumn) ComplexColumn(io.druid.segment.column.ComplexColumn) Column(io.druid.segment.column.Column) DictionaryEncodedColumn(io.druid.segment.column.DictionaryEncodedColumn) IndexedFloatsGenericColumn(io.druid.segment.column.IndexedFloatsGenericColumn) IndexedFloatsGenericColumn(io.druid.segment.column.IndexedFloatsGenericColumn) Iterator(java.util.Iterator) Collection(java.util.Collection) ISE(io.druid.java.util.common.ISE) NoSuchElementException(java.util.NoSuchElementException) ComplexColumn(io.druid.segment.column.ComplexColumn)

Example 4 with NoSuchElementException

use of java.util.NoSuchElementException in project tomcat by apache.

the class GenericObjectPool method borrowObject.

/**
     * Borrow an object from the pool using the specific waiting time which only
     * applies if {@link #getBlockWhenExhausted()} is true.
     * <p>
     * If there is one or more idle instance available in the pool, then an
     * idle instance will be selected based on the value of {@link #getLifo()},
     * activated and returned. If activation fails, or {@link #getTestOnBorrow()
     * testOnBorrow} is set to <code>true</code> and validation fails, the
     * instance is destroyed and the next available instance is examined. This
     * continues until either a valid instance is returned or there are no more
     * idle instances available.
     * <p>
     * If there are no idle instances available in the pool, behavior depends on
     * the {@link #getMaxTotal() maxTotal}, (if applicable)
     * {@link #getBlockWhenExhausted()} and the value passed in to the
     * <code>borrowMaxWaitMillis</code> parameter. If the number of instances
     * checked out from the pool is less than <code>maxTotal,</code> a new
     * instance is created, activated and (if applicable) validated and returned
     * to the caller. If validation fails, a <code>NoSuchElementException</code>
     * is thrown.
     * <p>
     * If the pool is exhausted (no available idle instances and no capacity to
     * create new ones), this method will either block (if
     * {@link #getBlockWhenExhausted()} is true) or throw a
     * <code>NoSuchElementException</code> (if
     * {@link #getBlockWhenExhausted()} is false). The length of time that this
     * method will block when {@link #getBlockWhenExhausted()} is true is
     * determined by the value passed in to the <code>borrowMaxWaitMillis</code>
     * parameter.
     * <p>
     * When the pool is exhausted, multiple calling threads may be
     * simultaneously blocked waiting for instances to become available. A
     * "fairness" algorithm has been implemented to ensure that threads receive
     * available instances in request arrival order.
     *
     * @param borrowMaxWaitMillis The time to wait in milliseconds for an object
     *                            to become available
     *
     * @return object instance from the pool
     *
     * @throws NoSuchElementException if an instance cannot be returned
     *
     * @throws Exception if an object instance cannot be returned due to an
     *                   error
     */
public T borrowObject(final long borrowMaxWaitMillis) throws Exception {
    assertOpen();
    final AbandonedConfig ac = this.abandonedConfig;
    if (ac != null && ac.getRemoveAbandonedOnBorrow() && (getNumIdle() < 2) && (getNumActive() > getMaxTotal() - 3)) {
        removeAbandoned(ac);
    }
    PooledObject<T> p = null;
    // Get local copy of current config so it is consistent for entire
    // method execution
    final boolean blockWhenExhausted = getBlockWhenExhausted();
    boolean create;
    final long waitTime = System.currentTimeMillis();
    while (p == null) {
        create = false;
        p = idleObjects.pollFirst();
        if (p == null) {
            p = create();
            if (p != null) {
                create = true;
            }
        }
        if (blockWhenExhausted) {
            if (p == null) {
                if (borrowMaxWaitMillis < 0) {
                    p = idleObjects.takeFirst();
                } else {
                    p = idleObjects.pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
                }
            }
            if (p == null) {
                throw new NoSuchElementException("Timeout waiting for idle object");
            }
        } else {
            if (p == null) {
                throw new NoSuchElementException("Pool exhausted");
            }
        }
        if (!p.allocate()) {
            p = null;
        }
        if (p != null) {
            try {
                factory.activateObject(p);
            } catch (final Exception e) {
                try {
                    destroy(p);
                } catch (final Exception e1) {
                // Ignore - activation failure is more important
                }
                p = null;
                if (create) {
                    final NoSuchElementException nsee = new NoSuchElementException("Unable to activate object");
                    nsee.initCause(e);
                    throw nsee;
                }
            }
            if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
                boolean validate = false;
                Throwable validationThrowable = null;
                try {
                    validate = factory.validateObject(p);
                } catch (final Throwable t) {
                    PoolUtils.checkRethrow(t);
                    validationThrowable = t;
                }
                if (!validate) {
                    try {
                        destroy(p);
                        destroyedByBorrowValidationCount.incrementAndGet();
                    } catch (final Exception e) {
                    // Ignore - validation failure is more important
                    }
                    p = null;
                    if (create) {
                        final NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
                        nsee.initCause(validationThrowable);
                        throw nsee;
                    }
                }
            }
        }
    }
    updateStatsBorrow(p, System.currentTimeMillis() - waitTime);
    return p.getObject();
}
Also used : NoSuchElementException(java.util.NoSuchElementException) NoSuchElementException(java.util.NoSuchElementException)

Example 5 with NoSuchElementException

use of java.util.NoSuchElementException in project elasticsearch by elastic.

the class IterablesTests method testGetOverIterable.

public void testGetOverIterable() {
    Iterable<String> iterable = () -> new Iterator<String>() {

        private int position = 0;

        @Override
        public boolean hasNext() {
            return position < 3;
        }

        @Override
        public String next() {
            if (position < 3) {
                String s = position == 0 ? "a" : position == 1 ? "b" : "c";
                position++;
                return s;
            } else {
                throw new NoSuchElementException();
            }
        }
    };
    test(iterable);
}
Also used : Iterator(java.util.Iterator) HasToString.hasToString(org.hamcrest.object.HasToString.hasToString) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

NoSuchElementException (java.util.NoSuchElementException)1624 Iterator (java.util.Iterator)234 ArrayList (java.util.ArrayList)138 IOException (java.io.IOException)136 Test (org.junit.Test)95 StringTokenizer (java.util.StringTokenizer)88 Scanner (java.util.Scanner)86 Map (java.util.Map)56 List (java.util.List)54 File (java.io.File)51 HashMap (java.util.HashMap)47 InputMismatchException (java.util.InputMismatchException)47 LinkedList (java.util.LinkedList)32 HashSet (java.util.HashSet)31 Set (java.util.Set)29 CorruptDataException (com.ibm.j9ddr.CorruptDataException)28 Locale (java.util.Locale)27 Collection (java.util.Collection)26 BufferedReader (java.io.BufferedReader)24 Enumeration (java.util.Enumeration)24