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:mondrian.olap.Util.java

/**
 * Applies a collection of filters to an iterable.
 *
 * @param iterable Iterable//  w w  w  .  j  a v a 2 s . c  o m
 * @param conds Zero or more conditions
 * @param <T>
 * @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 Functor1<Boolean, T>... conds) {
    final Functor1<Boolean, 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 (Functor1<Boolean, T> cond : conds2) {
                            if (!cond.apply(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.oltpbenchmark.benchmarks.seats.SEATSLoader.java

public Iterable<FlightId> getFlightIds() {
    return (new Iterable<FlightId>() {
        @Override// w w w .ja v a  2 s.c o m
        public Iterator<FlightId> iterator() {
            return (new Iterator<FlightId>() {
                private int idx = 0;
                private final int cnt = seats_remaining.size();

                @Override
                public boolean hasNext() {
                    return (idx < this.cnt);
                }

                @Override
                public FlightId next() {
                    return (seats_remaining.get(this.idx++));
                }

                @Override
                public void remove() {
                    // Not implemented
                }
            });
        }
    });
}

From source file:io.minio.MinioClient.java

/**
 * Lists object information as {@code Iterable<Result><Item>>} in given bucket, prefix and recursive flag.
 *
 * </p><b>Example:</b><br>
 * <pre>{@code Iterable<Result<Item>> myObjects = minioClient.listObjects("my-bucketname");
 * for (Result<Item> result : myObjects) {
 *   Item item = result.get();/*from  ww w. j a  va 2 s .  c o m*/
 *   System.out.println(item.lastModified() + ", " + item.size() + ", " + item.objectName());
 * } }</pre>
 *
 * @param bucketName Bucket name.
 * @param prefix     Prefix string.  List objects whose name starts with `prefix`.
 * @param recursive when false, emulates a directory structure where each listing returned is either a full object
 *                  or part of the object's key up to the first '/'. All objects wit the same prefix up to the first
 *                  '/' will be merged into one entry.
 *
 * @return an iterator of Result Items.
 *
 * @see #listObjects(String bucketName)
 * @see #listObjects(String bucketName, String prefix)
 */
public Iterable<Result<Item>> listObjects(final String bucketName, final String prefix,
        final boolean recursive) {
    return new Iterable<Result<Item>>() {
        @Override
        public Iterator<Result<Item>> iterator() {
            return new Iterator<Result<Item>>() {
                private String lastObjectName;
                private ListBucketResult listBucketResult;
                private Result<Item> error;
                private Iterator<Item> itemIterator;
                private Iterator<Prefix> prefixIterator;
                private boolean completed = false;

                private synchronized void populate() {
                    String delimiter = "/";
                    if (recursive) {
                        delimiter = null;
                    }

                    String marker = null;
                    if (this.listBucketResult != null) {
                        if (delimiter != null) {
                            marker = listBucketResult.nextMarker();
                        } else {
                            marker = this.lastObjectName;
                        }
                    }

                    this.listBucketResult = null;
                    this.itemIterator = null;
                    this.prefixIterator = null;

                    try {
                        this.listBucketResult = listObjects(bucketName, marker, prefix, delimiter, null);
                    } catch (InvalidBucketNameException | NoSuchAlgorithmException | InsufficientDataException
                            | IOException | InvalidKeyException | NoResponseException | XmlPullParserException
                            | ErrorResponseException | InternalException e) {
                        this.error = new Result<>(null, e);
                    } finally {
                        if (this.listBucketResult != null) {
                            this.itemIterator = this.listBucketResult.contents().iterator();
                            this.prefixIterator = this.listBucketResult.commonPrefixes().iterator();
                        } else {
                            this.itemIterator = new LinkedList<Item>().iterator();
                            this.prefixIterator = new LinkedList<Prefix>().iterator();
                        }
                    }
                }

                @Override
                public boolean hasNext() {
                    if (this.completed) {
                        return false;
                    }

                    if (this.error == null && this.itemIterator == null && this.prefixIterator == null) {
                        populate();
                    }

                    if (this.error == null && !this.itemIterator.hasNext() && !this.prefixIterator.hasNext()
                            && this.listBucketResult.isTruncated()) {
                        populate();
                    }

                    if (this.error != null) {
                        return true;
                    }

                    if (this.itemIterator.hasNext()) {
                        return true;
                    }

                    if (this.prefixIterator.hasNext()) {
                        return true;
                    }

                    this.completed = true;
                    return false;
                }

                @Override
                public Result<Item> next() {
                    if (this.completed) {
                        throw new NoSuchElementException();
                    }

                    if (this.error == null && this.itemIterator == null && this.prefixIterator == null) {
                        populate();
                    }

                    if (this.error == null && !this.itemIterator.hasNext() && !this.prefixIterator.hasNext()
                            && this.listBucketResult.isTruncated()) {
                        populate();
                    }

                    if (this.error != null) {
                        this.completed = true;
                        return this.error;
                    }

                    if (this.itemIterator.hasNext()) {
                        Item item = this.itemIterator.next();
                        this.lastObjectName = item.objectName();
                        return new Result<>(item, null);
                    }

                    if (this.prefixIterator.hasNext()) {
                        Prefix prefix = this.prefixIterator.next();
                        Item item;
                        try {
                            item = new Item(prefix.prefix(), true);
                        } catch (XmlPullParserException e) {
                            // special case: ignore the error as we can't propagate the exception in next()
                            item = null;
                        }

                        return new Result<>(item, null);
                    }

                    this.completed = true;
                    throw new NoSuchElementException();
                }

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

From source file:hybridewah.HybridBitmap.java

/**
 * iterate over the positions of the true values. This is similar to
 * intIterator(), but it uses Java generics.
 * /*from  ww  w  . j  a v a 2 s  .  co  m*/
 * @return the iterator
 */
public Iterator<Integer> iterator() {
    return new Iterator<Integer>() {
        public boolean hasNext() {
            return this.under.hasNext();
        }

        public Integer next() {
            return new Integer(this.under.next());
        }

        public void remove() {
            throw new UnsupportedOperationException("bitsets do not support remove");
        }

        final private IntIterator under = intIterator();
    };
}

From source file:jetbrains.exodus.entitystore.PersistentEntityStoreImpl.java

public void deleteEntityType(@NotNull final String entityTypeName) {
    final PersistentStoreTransaction txn = getAndCheckCurrentTransaction();
    final int entityTypeId = entityTypes.delete(txn, entityTypeName);

    if (entityTypeId < 0) {
        return;//from   w ww  .  ja va2s.  c  om
    }

    entitiesTables.remove(entityTypeId);
    entitiesHistoryTables.remove(entityTypeId);
    propertiesTables.remove(entityTypeId);
    propertiesHistoryTables.remove(entityTypeId);
    linksTables.remove(entityTypeId);
    linksHistoryTables.remove(entityTypeId);
    blobsTables.remove(entityTypeId);
    blobsHistoryTables.remove(entityTypeId);

    final String entityTableName = namingRulez.getEntitiesTableName(entityTypeId);
    final String propertiesTableName = namingRulez.getPropertiesTableName(entityTypeId);
    final String linksTableName = namingRulez.getLinksTableName(entityTypeId);
    final String secondLinksTableName = TwoColumnTable.secondColumnDatabaseName(linksTableName);
    final String blobsTableName = namingRulez.getBlobsTableName(entityTypeId);

    truncateStores(txn, Arrays.<String>asList(entityTableName, linksTableName, secondLinksTableName,
            propertiesTableName, blobsTableName), new Iterable<String>() {
                @Override
                public Iterator<String> iterator() {
                    return new Iterator<String>() { // enumerate all property value indexes
                        private int propertyId = 0;

                        @Override
                        public boolean hasNext() {
                            return propertyId < 10000; // this was taken from
                        }

                        @Override
                        public String next() {
                            return propertiesTableName + "#value_idx" + propertyId++;
                        }

                        @Override
                        public void remove() { // don't give a damn
                        }
                    };
                }
            });
}

From source file:com.servoy.j2db.util.Utils.java

/**
 * Iterate over enumeration.//from   w  w  w. j a  v a2  s. c o m
 * <pre>
 * for (T o: Utils.iterate(enumeration))
 * {
 *     o. ....
 * }
 * </pre>
 * @param enumeration when null, iterate over empty list
 */
public static <T> Iterable<T> iterate(final Enumeration<T> enumeration) {
    return iterate(enumeration == null ? null : new Iterator<T>() {
        @Override
        public boolean hasNext() {
            return enumeration.hasMoreElements();
        }

        @Override
        public T next() {
            return enumeration.nextElement();
        }

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

From source file:act.server.MongoDB.java

public Iterator<Chemical> getJavaIteratorOverChemicals(BasicDBObject matchCriterion) {
    final DBIterator iter = getIteratorOverChemicals(matchCriterion, null);

    return new Iterator<Chemical>() {
        @Override//from  www  .ja  v  a 2s.c o m
        public boolean hasNext() {
            boolean hasNext = iter.hasNext();
            if (!hasNext)
                iter.close();
            return hasNext;
        }

        @Override
        public Chemical next() {
            DBObject o = iter.next();
            return convertDBObjectToChemical(o);
        }
    };
}

From source file:act.server.MongoDB.java

public Iterator<String> getIteratorOverInchis(BasicDBObject matchCriterion) {
    BasicDBObject keys = new BasicDBObject(ChemicalKeywords.INCHI$.MODULE$.toString(), true);
    final DBIterator iter = getIteratorOverChemicals(matchCriterion, keys);

    return new Iterator<String>() {
        @Override//from   w w  w .j  av  a  2  s.co  m
        public boolean hasNext() {
            boolean hasNext = iter.hasNext();
            if (!hasNext)
                iter.close();
            return hasNext;
        }

        @Override
        public String next() {
            DBObject o = iter.next();
            return (String) o.get("InChI");
        }
    };
}

From source file:org.apache.nifi.controller.repository.StandardProcessSession.java

private void removeExpired(final Set<FlowFileRecord> flowFiles, final Connection connection) {
    if (flowFiles.isEmpty()) {
        return;/*from  w w w . ja  va2s.  c  o  m*/
    }

    LOG.info("{} {} FlowFiles have expired and will be removed", new Object[] { this, flowFiles.size() });
    final List<RepositoryRecord> expiredRecords = new ArrayList<>(flowFiles.size());

    final Connectable connectable = context.getConnectable();
    final String processorType = connectable.getComponentType();
    final StandardProvenanceReporter expiredReporter = new StandardProvenanceReporter(this,
            connectable.getIdentifier(), processorType, context.getProvenanceRepository(), this);

    final Map<String, FlowFileRecord> recordIdMap = new HashMap<>();
    for (final FlowFileRecord flowFile : flowFiles) {
        recordIdMap.put(flowFile.getAttribute(CoreAttributes.UUID.key()), flowFile);

        final StandardRepositoryRecord record = new StandardRepositoryRecord(connection.getFlowFileQueue(),
                flowFile);
        record.markForDelete();
        expiredRecords.add(record);
        expiredReporter.expire(flowFile,
                "Expiration Threshold = " + connection.getFlowFileQueue().getFlowFileExpiration());
        decrementClaimCount(flowFile.getContentClaim());

        final long flowFileLife = System.currentTimeMillis() - flowFile.getEntryDate();
        final Object terminator = connectable instanceof ProcessorNode
                ? ((ProcessorNode) connectable).getProcessor()
                : connectable;
        LOG.info("{} terminated by {} due to FlowFile expiration; life of FlowFile = {} ms",
                new Object[] { flowFile, terminator, flowFileLife });
    }

    try {
        final Iterable<ProvenanceEventRecord> iterable = new Iterable<ProvenanceEventRecord>() {
            @Override
            public Iterator<ProvenanceEventRecord> iterator() {
                final Iterator<ProvenanceEventRecord> expiredEventIterator = expiredReporter.getEvents()
                        .iterator();
                final Iterator<ProvenanceEventRecord> enrichingIterator = new Iterator<ProvenanceEventRecord>() {
                    @Override
                    public boolean hasNext() {
                        return expiredEventIterator.hasNext();
                    }

                    @Override
                    public ProvenanceEventRecord next() {
                        final ProvenanceEventRecord event = expiredEventIterator.next();
                        final StandardProvenanceEventRecord.Builder enriched = new StandardProvenanceEventRecord.Builder()
                                .fromEvent(event);
                        final FlowFileRecord record = recordIdMap.get(event.getFlowFileUuid());
                        if (record == null) {
                            return null;
                        }

                        final ContentClaim claim = record.getContentClaim();
                        if (claim != null) {
                            final ResourceClaim resourceClaim = claim.getResourceClaim();
                            enriched.setCurrentContentClaim(resourceClaim.getContainer(),
                                    resourceClaim.getSection(), resourceClaim.getId(),
                                    record.getContentClaimOffset() + claim.getOffset(), record.getSize());
                            enriched.setPreviousContentClaim(resourceClaim.getContainer(),
                                    resourceClaim.getSection(), resourceClaim.getId(),
                                    record.getContentClaimOffset() + claim.getOffset(), record.getSize());
                        }

                        enriched.setAttributes(record.getAttributes(), Collections.<String, String>emptyMap());
                        return enriched.build();
                    }

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

                return enrichingIterator;
            }
        };

        context.getProvenanceRepository().registerEvents(iterable);
        context.getFlowFileRepository().updateRepository(expiredRecords);
    } catch (final IOException e) {
        LOG.error("Failed to update FlowFile Repository to record expired records due to {}", e);
    }

}

From source file:org.exoplatform.services.jcr.impl.core.query.lucene.SearchIndex.java

private void recoverErrorLog(ErrorLog errlog) throws IOException, RepositoryException {
    final Set<String> rem = new HashSet<String>();
    final Set<String> add = new HashSet<String>();

    errlog.readChanges(rem, add);/*from  w ww  . j  av  a2 s.c  o m*/

    // check is any notifies in log
    if (rem.isEmpty() && add.isEmpty()) {
        // there is no sense to continue
        return;
    }

    Iterator<String> removedStates = rem.iterator();

    // make a new iterator;
    Iterator<NodeData> addedStates = new Iterator<NodeData>() {
        private final Iterator<String> iter = add.iterator();

        public boolean hasNext() {
            return iter.hasNext();
        }

        public NodeData next() {
            String id;
            // we have to iterrate through items till will meet ones
            // existing in
            // workspace
            while (iter.hasNext()) {
                id = iter.next();

                try {
                    ItemData item = getContext().getItemStateManager().getItemData(id);
                    if (item != null) {
                        if (item.isNode()) {
                            return (NodeData) item; // return node here
                        } else {
                            log.warn("Node expected but property found with id " + id + ". Skipping "
                                    + item.getQPath().getAsString());
                        }
                    } else {
                        log.warn("Unable to recovery node index " + id + ". Node not found.");
                    }
                } catch (RepositoryException e) {
                    log.error("ErrorLog recovery error. Item id " + id + ". " + e, e);
                }
            }

            return null;
        }

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

    updateNodes(removedStates, addedStates);

    errlog.clear();
}