Example usage for java.util Iterator Iterator

List of usage examples for java.util Iterator Iterator

Introduction

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

Prototype

Iterator

Source Link

Usage

From source file:br.ufpe.cin.emergo.instrument.bitrep.BitVectorConfigRep.java

@Override
public Iterator<IConfigRep> iterator() {
    return new Iterator<IConfigRep>() {
        int index = 0;
        // number of bits initially set to true.
        int cardinality = bitVector.cardinality();

        @Override/*from w w  w.j  a  v a 2 s.co  m*/
        public boolean hasNext() {
            return cardinality > 0;
        }

        @Override
        public IConfigRep next() {
            // increment index until a bit that is set is found
            for (; !bitVector.getQuick(index); index++)
                ;
            BitVector bv = new BitVector(bitVector.size());
            // set that one bit to true in this new BitVector
            bv.set(index);
            cardinality--;
            index++;
            return new BitVectorConfigRep(atoms, bv);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:io.druid.data.input.impl.prefetch.PrefetchableTextFilesFirehoseFactory.java

@Override
public Firehose connect(StringInputRowParser firehoseParser, File temporaryDirectory) throws IOException {
    if (!cacheManager.isEnabled() && maxFetchCapacityBytes == 0) {
        return super.connect(firehoseParser, temporaryDirectory);
    }//  w w w  . ja  v  a  2s. c o m

    if (objects == null) {
        objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "objects"));
    }

    Preconditions.checkState(temporaryDirectory.exists(), "temporaryDirectory[%s] does not exist",
            temporaryDirectory);
    Preconditions.checkState(temporaryDirectory.isDirectory(), "temporaryDirectory[%s] is not a directory",
            temporaryDirectory);

    LOG.info("Create a new firehose for [%d] objects", objects.size());

    // fetchExecutor is responsible for background data fetching
    final ExecutorService fetchExecutor = Execs.singleThreaded("firehose_fetch_%d");
    final Fetcher<T> fetcher = new Fetcher<>(cacheManager, objects, fetchExecutor, temporaryDirectory,
            maxFetchCapacityBytes, prefetchTriggerBytes, fetchTimeout, maxFetchRetry, this::openObjectStream);

    return new FileIteratingFirehose(new Iterator<LineIterator>() {
        @Override
        public boolean hasNext() {
            return fetcher.hasNext();
        }

        @Override
        public LineIterator next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            final OpenedObject<T> openedObject = fetcher.next();
            final InputStream stream;
            try {
                stream = wrapObjectStream(openedObject.getObject(), openedObject.getObjectStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return new ResourceCloseableLineIterator(new InputStreamReader(stream, StandardCharsets.UTF_8),
                    openedObject.getResourceCloser());
        }
    }, firehoseParser, () -> {
        fetchExecutor.shutdownNow();
        try {
            Preconditions.checkState(fetchExecutor.awaitTermination(fetchTimeout, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ISE("Failed to shutdown fetch executor during close");
        }
    });
}

From source file:MiniMap.java

/**
 * @see java.util.Map#entrySet()//from   w ww.  j  a  v a  2 s  .c o  m
 */
public Set<Entry<K, V>> entrySet() {
    return new AbstractSet<Entry<K, V>>() {
        @Override
        public Iterator<Entry<K, V>> iterator() {
            return new Iterator<Entry<K, V>>() {
                public boolean hasNext() {
                    return index < size;
                }

                public Entry<K, V> next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException();
                    }

                    keyIndex = nextKey(nextIndex(keyIndex));

                    index++;

                    return new Map.Entry<K, V>() {
                        public K getKey() {
                            return keys[keyIndex];
                        }

                        public V getValue() {
                            return values[keyIndex];
                        }

                        public V setValue(final V value) {
                            final V oldValue = values[keyIndex];

                            values[keyIndex] = value;

                            return oldValue;
                        }
                    };
                }

                public void remove() {
                    keys[keyIndex] = null;
                    values[keyIndex] = null;
                }

                int keyIndex = -1;

                int index = 0;
            };
        }

        @Override
        public int size() {
            return size;
        }
    };
}

From source file:org.olap4j.xmla.server.impl.Util.java

/**
 * Applies a collection of filters to an iterable.
 *
 * @param iterable Iterable/*  w  w  w  . j av  a 2  s  .c  o  m*/
 * @param conds Zero or more conditions
 * @param <T> element type
 * @return Iterable that returns only members of underlying iterable for
 *     for which all conditions evaluate to true
 */
public static <T> Iterable<T> filter(final Iterable<T> iterable, final Predicate1<T>... conds) {
    final Predicate1<T>[] conds2 = optimizeConditions(conds);
    if (conds2.length == 0) {
        return iterable;
    }
    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                final Iterator<T> iterator = iterable.iterator();
                T next;
                boolean hasNext = moveToNext();

                private boolean moveToNext() {
                    outer: while (iterator.hasNext()) {
                        next = iterator.next();
                        for (Predicate1<T> cond : conds2) {
                            if (!cond.test(next)) {
                                continue outer;
                            }
                        }
                        return true;
                    }
                    return false;
                }

                public boolean hasNext() {
                    return hasNext;
                }

                public T next() {
                    T t = next;
                    hasNext = moveToNext();
                    return t;
                }

                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };
}

From source file:com.evolveum.polygon.connector.ldap.ConnectionManager.java

public Iterable<LdapNetworkConnection> getAllConnections() {

    final Iterator<ServerDefinition> serversIterator = servers.iterator();

    return new Iterable<LdapNetworkConnection>() {

        @Override//from  w  ww.  j a  v a  2 s .  c  om
        public Iterator<LdapNetworkConnection> iterator() {
            return new Iterator<LdapNetworkConnection>() {

                @Override
                public boolean hasNext() {
                    return serversIterator.hasNext();
                }

                @Override
                public LdapNetworkConnection next() {
                    return getConnection(serversIterator.next());
                }

                @Override
                public void remove() {
                    serversIterator.remove();
                }

            };
        }
    };

}

From source file:org.apache.druid.data.input.impl.prefetch.PrefetchableTextFilesFirehoseFactory.java

@Override
public Firehose connect(StringInputRowParser firehoseParser, @Nullable File temporaryDirectory)
        throws IOException {
    if (objects == null) {
        objects = ImmutableList.copyOf(Preconditions.checkNotNull(initObjects(), "objects"));
    }/*from w  ww .  java  2s.  c o  m*/

    if (cacheManager.isEnabled() || prefetchConfig.getMaxFetchCapacityBytes() > 0) {
        Preconditions.checkNotNull(temporaryDirectory, "temporaryDirectory");
        Preconditions.checkArgument(temporaryDirectory.exists(), "temporaryDirectory[%s] does not exist",
                temporaryDirectory);
        Preconditions.checkArgument(temporaryDirectory.isDirectory(),
                "temporaryDirectory[%s] is not a directory", temporaryDirectory);
    }

    LOG.info("Create a new firehose for [%d] objects", objects.size());

    // fetchExecutor is responsible for background data fetching
    final ExecutorService fetchExecutor = Execs.singleThreaded("firehose_fetch_%d");
    final FileFetcher<T> fetcher = new FileFetcher<T>(cacheManager, objects, fetchExecutor, temporaryDirectory,
            prefetchConfig, new ObjectOpenFunction<T>() {
                @Override
                public InputStream open(T object) throws IOException {
                    return openObjectStream(object);
                }

                @Override
                public InputStream open(T object, long start) throws IOException {
                    return openObjectStream(object, start);
                }
            }, getRetryCondition(), getMaxFetchRetry());

    return new FileIteratingFirehose(new Iterator<LineIterator>() {
        @Override
        public boolean hasNext() {
            return fetcher.hasNext();
        }

        @Override
        public LineIterator next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            final OpenedObject<T> openedObject = fetcher.next();
            try {
                return new ResourceCloseableLineIterator(new InputStreamReader(
                        wrapObjectStream(openedObject.getObject(), openedObject.getObjectStream()),
                        StandardCharsets.UTF_8), openedObject.getResourceCloser());
            } catch (IOException e) {
                try {
                    openedObject.getResourceCloser().close();
                } catch (Throwable t) {
                    e.addSuppressed(t);
                }
                throw new RuntimeException(e);
            }
        }
    }, firehoseParser, () -> {
        fetchExecutor.shutdownNow();
        try {
            Preconditions.checkState(
                    fetchExecutor.awaitTermination(prefetchConfig.getFetchTimeout(), TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ISE("Failed to shutdown fetch executor during close");
        }
    });
}

From source file:org.apache.accumulo.server.problems.ProblemReports.java

public Iterator<ProblemReport> iterator(final String table) {
    try {//  w  w w . jav  a 2s  .c  o m

        return new Iterator<ProblemReport>() {

            IZooReaderWriter zoo = ZooReaderWriter.getInstance();
            private int iter1Count = 0;
            private Iterator<String> iter1;

            private Iterator<String> getIter1() {
                if (iter1 == null) {
                    try {
                        List<String> children;
                        if (table == null || isMeta(table)) {
                            children = zoo
                                    .getChildren(ZooUtil.getRoot(context.getInstance()) + Constants.ZPROBLEMS);
                        } else {
                            children = Collections.emptyList();
                        }
                        iter1 = children.iterator();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                return iter1;
            }

            private Iterator<Entry<Key, Value>> iter2;

            private Iterator<Entry<Key, Value>> getIter2() {
                if (iter2 == null) {
                    try {
                        if ((table == null || !isMeta(table)) && iter1Count == 0) {
                            Connector connector = context.getConnector();
                            Scanner scanner = connector.createScanner(MetadataTable.NAME, Authorizations.EMPTY);

                            scanner.setTimeout(3, TimeUnit.SECONDS);

                            if (table == null) {
                                scanner.setRange(new Range(new Text("~err_"), false, new Text("~err`"), false));
                            } else {
                                scanner.setRange(new Range(new Text("~err_" + table)));
                            }

                            iter2 = scanner.iterator();

                        } else {
                            Map<Key, Value> m = Collections.emptyMap();
                            iter2 = m.entrySet().iterator();
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                return iter2;
            }

            @Override
            public boolean hasNext() {
                if (getIter1().hasNext()) {
                    return true;
                }

                if (getIter2().hasNext()) {
                    return true;
                }

                return false;
            }

            @Override
            public ProblemReport next() {
                try {
                    if (getIter1().hasNext()) {
                        iter1Count++;
                        return ProblemReport.decodeZooKeeperEntry(getIter1().next());
                    }

                    if (getIter2().hasNext()) {
                        return ProblemReport.decodeMetadataEntry(getIter2().next());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                throw new NoSuchElementException();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

        };

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jcwhatever.nucleus.internal.managed.commands.Arguments.java

@Override
public Iterator<ICommandArgument> iterator() {

    return new Iterator<ICommandArgument>() {

        int index = 0;

        @Override// w w  w .ja v a2  s. co  m
        public boolean hasNext() {
            return index < staticSize() + floatingSize();
        }

        @Override
        public Argument next() {
            if (!hasNext())
                throw new IndexOutOfBoundsException("No more elements.");

            Argument arg = index < staticSize() ? _parseResults.getStaticArgs().get(index)
                    : _parseResults.getFloatingArgs().get(index - (staticSize() > 0 ? 1 : 0));

            index++;
            //noinspection ConstantConditions
            return arg;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:fr.amap.lidar.format.jleica.LPointShotExtractor.java

@Override
public Iterator<LShot> iterator() {

    //scan.computeExtremumsAngles();
    //scan.setUpRowToRead(0);

    scan.setReturnInvalidPoint(true);/*from  w w  w. j a  va 2s  . co  m*/

    final Iterator<LPoint> pointIterator = scan.iterator();

    Iterator<LShot> it = new Iterator<LShot>() {

        int lastColumnIndex = -1;
        double last = 0.0;
        Vector3d lastVector = new Vector3d(0, 0, 0);

        @Override
        public boolean hasNext() {
            return pointIterator.hasNext();
        }

        @Override
        public LShot next() {

            LShot shot;

            LPoint point = pointIterator.next();

            if (point.valid) {

                double xDirection, yDirection, zDirection;
                if (scan.getHeader().isPointInDoubleFormat()) {
                    xDirection = ((LDoublePoint) point).x;
                    yDirection = ((LDoublePoint) point).y;
                    zDirection = ((LDoublePoint) point).z;
                } else {
                    xDirection = ((LFloatPoint) point).x;
                    yDirection = ((LFloatPoint) point).y;
                    zDirection = ((LFloatPoint) point).z;

                    //System.out.println(xDirection+"\t"+yDirection+"\t"+zDirection);
                }

                Vector3d direction = new Vector3d(xDirection, yDirection, zDirection);
                direction.normalize();

                double range = Math.sqrt(
                        (xDirection * xDirection) + (yDirection * yDirection) + (zDirection * zDirection));

                shot = new LShot(new Point3d(0, 0, 0), direction, new double[] { range });

                //test
                //recalculate shot
                /*double azimutalAngle = (scan.getAzim_min() - ((point.columnIndex - scan.getColIndexAzimMin()) * scan.getAzimutalStepAngle()));
                double elevationAngle = (scan.getElev_min() - ((point.rowIndex - scan.getRowIndexElevMin()) * scan.getElevationStepAngle()));
                        
                SphericalCoordinates sc = new SphericalCoordinates(azimutalAngle, elevationAngle);
                        
                Vector3d testDirection = new Vector3d(sc.toCartesian());
                testDirection.normalize();
                        
                Vec3D theoreticalVector = new Vec3D(testDirection.x, testDirection.y, testDirection.z);
                Vec3D obtainedVector = new Vec3D(direction.x, direction.y, direction.z);
                        
                double angle = Math.acos(Vec3D.dot(theoreticalVector, obtainedVector)/((Vec3D.length(obtainedVector) * Vec3D.length(theoreticalVector))));
                double degreesAngle = Math.toDegrees(angle);*/
                //System.out.println(degreesAngle);

            } else {
                //recalculate shot
                //double azimutalAngle = (scan.getAzim_min() - ((point.columnIndex - scan.getColIndexAzimMin()) * scan.getAzimutalStepAngle()));
                //double elevationAngle = (scan.getElev_min() - ((point.rowIndex - scan.getRowIndexElevMin()) * scan.getElevationStepAngle()));

                SphericalCoordinates sc = new SphericalCoordinates(1,
                        angles[point.rowIndex][point.columnIndex].azimut,
                        angles[point.rowIndex][point.columnIndex].zenith);
                //SphericalCoordinates sc = angles[point.rowIndex][point.columnIndex];
                Vector3d direction = new Vector3d(sc.getCartesian().getX(), sc.getCartesian().getY(),
                        sc.getCartesian().getZ());
                direction.normalize();

                shot = new LShot(new Point3d(0, 0, 0), direction, new double[] {});
                //shot = correctSlope(shot);
            }

            shot.point = point;

            return shot;
        }
    };

    return it;
}

From source file:org.nema.medical.mint.server.controller.StudyBinaryItemsController.java

/**
 * This method will scan through the study in the provided root directory
 * and will create a list of bid's encountered in order. This order is
 * expected to be the order in which the binary IDs exist in the study
 * metadata document.//from   w w  w.  j  a va  2  s .  co m
 * 
 * @param seq
 * @param type
 * @param studyRoot
 * @return
 * @throws NumberFormatException
 * @throws IOException
 */
private Iterator<Integer> parseItemList(String seq, String type, File studyRoot)
        throws NumberFormatException, IOException {
    final List<Integer> itemList = new ArrayList<Integer>();

    if (seq.equals("all")) {
        final File binaryRoot = new File(studyRoot, type + "/binaryitems");
        binaryRoot.list();

        return new Iterator<Integer>() {
            private Iterator<String> binaryNames = Arrays.asList(binaryRoot.list()).iterator();
            private String next = null;

            @Override
            public boolean hasNext() {
                getNext();

                return next != null;
            }

            @Override
            public Integer next() throws NumberFormatException {
                getNext();

                if (next == null)
                    throw new NoSuchElementException();

                int result = Integer.valueOf(next.substring(0, next.indexOf('.')));

                next = null;

                return result;
            }

            private void getNext() {
                if (next == null && binaryNames.hasNext()) {
                    do {
                        next = binaryNames.next();
                    } while (!next.endsWith(StorageUtil.BINARY_FILE_EXTENSION) && binaryNames.hasNext());

                    if (!next.endsWith(StorageUtil.BINARY_FILE_EXTENSION)) {
                        next = null;
                    }
                }
            }

            @Override
            public void remove() {
                binaryNames.remove();
            }
        };
    } else {
        /*
         * TODO speed this up by removing the need to build an entire list
         * ahead of time. This is a slow operation if there are 100000
         * items. This can be done by implementing a custom iterator similar
         * to how to all method works.
         */
        String[] elements = seq.split(",");

        for (String element : elements) {
            String[] range = element.split("-");

            if (range.length < 1 || range.length > 2) {
                //failed to parse element, error message not set yet
                return null;
            }

            int start = Integer.valueOf(range[0]);
            int end = start;
            if (range.length == 2) {
                end = Integer.valueOf(range[1]);
            }

            if (start < 0 || end < 0) {
                //failed to parse element, error message already set
                return null;
            }

            //for each item in the range, add to itemList
            for (; start <= end; ++start) {
                itemList.add(start);
            }
        }
    }

    return itemList.iterator();
}