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:net.javacoding.queue.DiskQueue.java

/**
 * @see org.archive.queue.Queue#getIterator(boolean)
 * @return iterator/* ww w. jav  a 2 s .c o  m*/
 */
public Iterator getIterator(boolean inCacheOnly) {
    // There are no levels of storage so we will return all items.
    Iterator it = null;

    if (isInitialized) {
        try {
            it = new DiskQueueIterator(bytes.getReadAllInputStream(), length);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (it == null) {
        it = new Iterator() {
            public void remove() {
                throw new UnsupportedOperationException();
            }

            public boolean hasNext() {
                return false;
            }

            public Object next() {
                throw new NoSuchElementException();
            }
        };
    }

    return it;
}

From source file:org.kie.commons.java.nio.base.AbstractPath.java

@Override
public Iterator<Path> iterator() {
    return new Iterator<Path>() {
        private int i = 0;

        @Override// w w  w .j a va  2  s  .c o  m
        public boolean hasNext() {
            return i < getNameCount();
        }

        @Override
        public Path next() {
            if (i < getNameCount()) {
                Path result = getName(i);
                i++;
                return result;
            } else {
                throw new NoSuchElementException();
            }
        }

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

From source file:org.apache.accumulo.core.util.Merge.java

protected Iterator<Size> getSizeIterator(Connector conn, String tablename, Text start, Text end)
        throws MergeException {
    // open up metatadata, walk through the tablets.
    String tableId;/*  ww  w .  j  a va 2  s  .  co  m*/
    Scanner scanner;
    try {
        tableId = Tables.getTableId(conn.getInstance(), tablename);
        scanner = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
    } catch (Exception e) {
        throw new MergeException(e);
    }
    scanner.setRange(new KeyExtent(new Text(tableId), end, start).toMetadataRange());
    scanner.fetchColumnFamily(DataFileColumnFamily.NAME);
    TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.fetch(scanner);
    final Iterator<Entry<Key, Value>> iterator = scanner.iterator();

    Iterator<Size> result = new Iterator<Size>() {
        Size next = fetch();

        @Override
        public boolean hasNext() {
            return next != null;
        }

        private Size fetch() {
            long tabletSize = 0;
            while (iterator.hasNext()) {
                Entry<Key, Value> entry = iterator.next();
                Key key = entry.getKey();
                if (key.getColumnFamily().equals(DataFileColumnFamily.NAME)) {
                    String[] sizeEntries = new String(entry.getValue().get(), Constants.UTF8).split(",");
                    if (sizeEntries.length == 2) {
                        tabletSize += Long.parseLong(sizeEntries[0]);
                    }
                } else if (TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.hasColumns(key)) {
                    KeyExtent extent = new KeyExtent(key.getRow(), entry.getValue());
                    return new Size(extent, tabletSize);
                }
            }
            return null;
        }

        @Override
        public Size next() {
            Size result = next;
            next = fetch();
            return result;
        }

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

From source file:net.jcreate.xkins.XkinsLoader.java

/**
 * Devuelve un Iterator con URL de cada configuration file
 * @return//from   w w w  .  j  ava 2s .com
 */
private Iterator getConfigFiles() {
    return new Iterator() {
        StringTokenizer st = new StringTokenizer(XkinsLoader.getConfig(), ",");

        public boolean hasNext() {
            return st.hasMoreTokens();
        }

        public Object next() {
            //tries to look for the file in the WEB-INF directory
            String configFile = st.nextToken().trim();
            URL url = null;
            try {
                if (servletContext != null) {//?web??,?
                    url = servletContext.getResource(configFile);
                }
                if (url == null) {
                    url = XkinsLoader.this.getClass().getResource(configFile);
                }
            } catch (MalformedURLException e) {
                url = XkinsLoader.this.getClass().getResource(configFile);
            }
            return url;
        }

        public void remove() {
        }
    };
}

From source file:aarddict.Volume.java

Iterator<Entry> lookup(final LookupWord lookupWord, final Comparator<Entry> comparator) {
    if (lookupWord.isEmpty()) {
        return EMPTY_ITERATOR;
    }/*  www  .j  ava2 s.com*/

    final String section = lookupWord.section;
    final Entry lookupEntry = new Entry(this.getId(), lookupWord.word);
    final int initialIndex = binarySearch(this, lookupEntry, comparator);
    Iterator<Entry> iterator = new Iterator<Entry>() {

        int index = initialIndex;
        Entry nextEntry;

        {
            prepareNext();
        }

        private void prepareNext() {
            if (index < header.indexCount) {
                Entry matchedEntry = get(index);
                nextEntry = (0 == comparator.compare(matchedEntry, lookupEntry)) ? matchedEntry : null;
                index++;
            } else {
                nextEntry = null;
            }
        }

        public boolean hasNext() {
            return nextEntry != null;
        }

        public Entry next() {
            Entry current = nextEntry;
            current.section = section;
            prepareNext();
            return current;
        }

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

    return iterator;
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.ERTICaptionInfoTreeLevelGrp.java

/**
 * @param value/*from   w ww. j a va  2s.c om*/
 * @throws SQLException
 */
@SuppressWarnings("unchecked")
protected Object[] newValue(final Object value) throws SQLException {
    Object[] currentRanks = null;
    //synchronized(currentRanks) 
    //{
    if (useCache) {
        Object[] lookedUp = (Object[]) lookupCache.lookupKey((Integer) value);
        //AtomicReferenceArray<Object[]> lookedUp = (AtomicReferenceArray<Object[]>)lookupCache.lookupKey((Integer )value);
        if (lookedUp != null) {
            currentRanks = lookedUp;
            return currentRanks;
        }
    }
    if (currentRanks == null) {
        currentRanks = new Object[members.size()];
        //currentRanks = new AtomicReferenceArray<Object[]>(members.size());
        for (int r = 0; r < members.size(); r++) {
            currentRanks[r] = null;
            //currentRanks.set(r, null);
        }
    }
    //}
    ResultSet ancestorRows = null;
    Iterator<Object> ancestors = null;
    Pair<Integer, String[]> ancestor = null;
    Statement statement = null;
    if (useHibernate) {
        query.setParameter("descendantArg", value);
        ancestors = (Iterator<Object>) query.list().iterator();
    } else {
        String sql = setupQuery(value);
        statement = DBConnection.getInstance().getConnection().createStatement();
        final ResultSet rows = statement.executeQuery(sql);
        ancestorRows = rows;
        ancestors = new Iterator<Object>() {

            @Override
            public boolean hasNext() {
                try {
                    return rows.next();
                } catch (SQLException ex) {
                    return false;
                }
            }

            @Override
            public Object next() {
                try {
                    int arraySize = fieldsToRetrieve == null ? 2 : fieldsToRetrieve.size() + 1;
                    Object[] result = new Object[arraySize];
                    for (int c = 0; c < arraySize - 1; c++) {
                        result[c] = rows.getString(c + 1);
                    }
                    result[arraySize - 1] = Integer.valueOf(rows.getString(arraySize));
                    return result;
                } catch (SQLException ex) {
                    return null;
                }
            }

            @Override
            public void remove() {
                // ignore               
            }

        };

    }

    //XXX using a pair for ancestor will not work when fieldsToRetrieve is non null
    ancestor = ancestors.hasNext() ? getAncestorInfo(ancestors.next()) : null;
    //members are ordered by rank
    for (ERTICaptionInfoTreeLevel member : members) {
        //if (ancestor != null) System.out.println(ancestor.getFirst() + " " + member.getRank());
        while (ancestor != null && ancestor.getFirst() < member.getRank()) {
            ancestor = ancestors.hasNext() ? getAncestorInfo(ancestors.next()) : null;
        }
        if (ancestor != null && ancestor.getFirst() == member.getRank()) {
            currentRanks[member.getRankIdx()] = ancestor.getSecond();
            //currentRanks.
        } else {
            currentRanks[member.getRankIdx()] = null;
        }
    }
    if (ancestorRows != null) {
        ancestorRows.close();
    }
    if (statement != null) {
        statement.close();
    }

    //        if (useCache)
    //        {
    //            lookupCache.addKey((Integer )value, currentRanks);
    //        }
    return currentRanks;
}

From source file:com.spotify.heroic.metric.astyanax.AstyanaxBackend.java

@Override
public Iterable<BackendEntry> listEntries() {
    final Borrowed<Context> ctx = context.borrow();

    final OperationResult<Rows<MetricsRowKey, Integer>> result;

    try {/*  www .  j a v  a  2s  .  c om*/
        result = ctx.get().client.prepareQuery(METRICS_CF).getAllRows().execute();
    } catch (final ConnectionException e) {
        throw new RuntimeException("Request failed", e);
    }

    return new Iterable<BackendEntry>() {
        @Override
        public Iterator<BackendEntry> iterator() {
            final Iterator<Row<MetricsRowKey, Integer>> iterator = result.getResult().iterator();

            return new Iterator<BackendEntry>() {
                @Override
                public boolean hasNext() {
                    final boolean next = iterator.hasNext();

                    if (!next) {
                        ctx.release();
                    }

                    return next;
                }

                @Override
                public BackendEntry next() {
                    final Row<MetricsRowKey, Integer> entry = iterator.next();
                    final MetricsRowKey rowKey = entry.getKey();
                    final Series series = rowKey.getSeries();

                    final List<Point> points = rowKey.buildPoints(entry.getColumns());
                    return new BackendEntry(series, MetricCollection.points(points));
                }

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

From source file:com.quinsoft.zeidon.standardoe.ViewImpl.java

@Override
public Iterable<EntityInstance> getHierEntityList(boolean includeRoot, String entityName) {
    EntityDef entityDef = null;/*from ww w.  ja v  a  2  s  .  co  m*/
    if (!StringUtils.isBlank(entityName))
        entityDef = getLodDef().getEntityDef(entityName);

    ObjectInstance oi = viewCursor.getObjectInstance();
    final EntityIterator<EntityInstanceImpl> iter = new IteratorBuilder(getObjectInstance()).withOiScoping(oi)
            .forEntityDef(entityDef).setLazyLoad(true).build();

    // Skip the root?
    if (!includeRoot)
        iter.next();

    // We have to create an iterator so that we can set the cursor in next().
    return new Iterable<EntityInstance>() {
        @Override
        public Iterator<EntityInstance> iterator() {
            return new Iterator<EntityInstance>() {
                @Override
                public boolean hasNext() {
                    return iter.hasNext();
                }

                @Override
                public EntityInstance next() {
                    EntityInstanceImpl ei = iter.next();
                    EntityDef entityDef = ei.getEntityDef();
                    EntityCursorImpl entityCursor = viewCursor.getEntityCursor(entityDef);
                    entityCursor.setCursor(ei);
                    return entityCursor.getEntityInstance();
                }

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

From source file:com.vaushell.superpipes.tools.scribe.linkedin.LinkedInClient.java

/**
 * Iterate a LinkedIn Feed.//from  w  ww. j  ava 2  s  .com
 *
 * @param forcedTarget Target's ID. Could be null to use login target.
 * @param count Max status by call. Could be null to use default.
 * @return a status iterator.
 */
public Iterator<LNK_Status> iteratorFeed(final String forcedTarget, final Integer count) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] iteratorFeed() : forcedTarget=" + forcedTarget
                + " / count=" + count);
    }

    return new Iterator<LNK_Status>() {
        @Override
        public boolean hasNext() {
            try {
                if (bufferCursor < buffer.size()) {
                    return true;
                } else {
                    buffer.clear();
                    bufferCursor = 0;

                    final String url;
                    final Properties properties = new Properties();
                    properties.setProperty("scope", "self");
                    properties.setProperty("type", "SHAR");
                    properties.setProperty("format", "json");
                    if (count != null) {
                        properties.setProperty("count", Integer.toString(count));
                    }

                    if (forcedTarget == null) {
                        url = "http://api.linkedin.com/v1/people/~/network/updates";
                    } else {
                        url = "http://api.linkedin.com/v1/people/id=" + forcedTarget + "/network/updates";
                    }

                    if (lastTimestamp != null) {
                        properties.setProperty("before", Long.toString(lastTimestamp.getMillis() - 1L));
                    }

                    final List<LNK_Status> posts = readFeedImpl(url, properties);
                    if (posts.isEmpty()) {
                        return false;
                    } else {
                        lastTimestamp = posts.get(posts.size() - 1).getTimestamp();

                        buffer.addAll(posts);

                        return true;
                    }
                }
            } catch (final LinkedInException | IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        @Override
        public LNK_Status next() {
            return buffer.get(bufferCursor++);
        }

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

        // PRIVATE
        private final List<LNK_Status> buffer = new ArrayList<>();
        private int bufferCursor;
        private DateTime lastTimestamp;
    };
}

From source file:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Integer> getIntegers(String key) {
    try {/*from  w ww.  j  a  v  a2  s  . co m*/
        final JSONArray array = obj.getJSONArray(key);

        return new Iterable<Integer>() {
            @Override
            public Iterator<Integer> iterator() {
                return new Iterator<Integer>() {
                    private final int n = array.length();
                    private int i = 0;

                    @Override
                    public boolean hasNext() {
                        return n > i;
                    }

                    @Override
                    public Integer next() {
                        try {
                            return (n > i) ? array.getInt(i++) : null;
                        } catch (JSONException e) {
                            return null;
                        }
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}