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:com.zextras.modules.chat.server.history.HistoryMailManager.java

private Iterator<Item> buildQueryResultsIterator(final QueryResults queryResults) {
    return new Iterator<Item>() {
        @Override//from www .  j  a v a2 s. c  o  m
        public boolean hasNext() {
            return queryResults.hasNext();
        }

        @Override
        public Item next() {
            return queryResults.getNext().getMailItem();
        }

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

From source file:CircularQueue.java

public Iterator iterator() {
    return new Iterator() {
        private final int ci = consumerIndex;
        private final int pi = producerIndex;
        private int s = size;
        private int i = ci;

        public boolean hasNext() {
            checkForModification();//from w  ww .j  a va  2s .  c o m
            return s > 0;
        }

        public Object next() {
            checkForModification();
            if (s == 0)
                throw new NoSuchElementException();

            s--;
            Object r = q[i];
            i = (i + 1) & bitmask;

            return r;
        }

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

        private void checkForModification() {
            if (ci != consumerIndex)
                throw new ConcurrentModificationException();
            if (pi != producerIndex)
                throw new ConcurrentModificationException();
        }
    };
}

From source file:com.github.nukesparrow.htmlunit.HUQueryElements.java

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

        int index = -1;

        @Override//  w ww . j  a  v  a  2 s.  co  m
        public boolean hasNext() {
            return index + 1 < elements.size();
        }

        @Override
        public HUQueryElements<Elem> next() {
            index++;
            return new HUQueryElements(w, elements.get(index));
        }
    };
}

From source file:act.installer.GenbankInstaller.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*ww  w  . ja v a 2 s  .  c om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(GenbankInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(GenbankInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File genbankFile = new File(cl.getOptionValue(OPTION_GENBANK_PATH));
    String dbName = cl.getOptionValue(OPTION_DB_NAME);
    String seqType = cl.getOptionValue(OPTION_SEQ_TYPE);

    if (!genbankFile.exists()) {
        String msg = String.format("Genbank file path is null");
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        MongoDB db = new MongoDB("localhost", 27017, dbName);

        DBIterator iter = db.getDbIteratorOverOrgs();

        Iterator<Organism> orgIterator = new Iterator<Organism>() {
            @Override
            public boolean hasNext() {
                boolean hasNext = iter.hasNext();
                if (!hasNext)
                    iter.close();
                return hasNext;
            }

            @Override
            public Organism next() {
                DBObject o = iter.next();
                return db.convertDBObjectToOrg(o);
            }

        };

        OrgMinimalPrefixGenerator prefixGenerator = new OrgMinimalPrefixGenerator(orgIterator);
        Map<String, String> minimalPrefixMapping = prefixGenerator.getMinimalPrefixMapping();

        GenbankInstaller installer = new GenbankInstaller(genbankFile, seqType, db, minimalPrefixMapping);
        installer.init();
    }

}

From source file:org.apache.pig.tools.pigstats.OutputStats.java

public Iterator<Tuple> iterator() throws IOException {
    final LoadFunc p;
    PigContext pigContext = ScriptState.get().getPigContext();
    if (pigContext == null || store == null) {
        throw new IllegalArgumentException();
    }//from  w  w  w  .  j a  v a  2 s  .co  m
    try {
        LoadFunc originalLoadFunc = (LoadFunc) PigContext
                .instantiateFuncFromSpec(store.getSFile().getFuncSpec());

        p = (LoadFunc) new ReadToEndLoader(originalLoadFunc,
                ConfigurationUtil.toConfiguration(pigContext.getProperties()), store.getSFile().getFileName(),
                0);

    } catch (Exception e) {
        int errCode = 2088;
        String msg = "Unable to get results for: " + store.getSFile();
        throw new ExecException(msg, errCode, PigException.BUG, e);
    }

    return new Iterator<Tuple>() {
        Tuple t;
        boolean atEnd;

        @Override
        public boolean hasNext() {
            if (atEnd)
                return false;
            try {
                if (t == null)
                    t = p.getNext();
                if (t == null)
                    atEnd = true;
            } catch (Exception e) {
                LOG.error(e);
                t = null;
                atEnd = true;
                throw new Error(e);
            }
            return !atEnd;
        }

        @Override
        public Tuple next() {
            Tuple next = t;
            if (next != null) {
                t = null;
                return next;
            }
            try {
                next = p.getNext();
            } catch (Exception e) {
                LOG.error(e);
            }
            if (next == null)
                atEnd = true;
            return next;
        }

        @Override
        public void remove() {
            throw new RuntimeException("Removal not supported");
        }

    };
}

From source file:org.paxml.bean.excel.ReadExcelTag.java

private Iterator doBasic(Context context) throws Exception {

    return new Iterator() {
        private Iterator<Row> it;
        private int index;
        private Map<Integer, String> headers = new HashMap<Integer, String>();

        private void start() {

            boolean ok = false;
            try {

                Sheet s = getExcelSheet(false);

                it = s.iterator();/*from   w ww .j  a  v  a  2  s.  c  o m*/
                // find the start row
                if (log.isDebugEnabled()) {
                    log.debug("Start reading from row " + Math.max(1, firstRow) + " of sheet: "
                            + s.getSheetName());
                }

                for (int i = 1; i < firstRow && it.hasNext(); i++) {
                    it.next();
                    index++;
                }

                ok = true;
            } finally {
                if (!ok) {
                    end();
                }
            }
        }

        private void end() {
            it = null;
            file.close();
        }

        @Override
        public boolean hasNext() {
            if (it == null) {
                start();
            }
            if (lastRow > 0 && index > lastRow - 1) {
                end();
                return false;
            }
            try {
                boolean has = it.hasNext();
                if (!has) {
                    end();
                }
                return has;
            } catch (Exception e) {
                end();
                throw new PaxmlRuntimeException(e);
            }
        }

        @Override
        public Object next() {
            try {
                Row row = it.next();
                Object r = readRow(row);
                index++;
                return r;
            } catch (Exception e) {
                end();
                throw new PaxmlRuntimeException(e);
            }
        }

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

        private Map<Object, Object> readRow(Row row) {

            final int firstCell = Math.max(row.getFirstCellNum(), _firstColumn);
            final int lastCell = _lastColumn < 0 ? row.getLastCellNum() - 1
                    : Math.min(row.getLastCellNum() - 1, _lastColumn);

            if (log.isDebugEnabled()) {
                log.debug("Reading cells: " + new CellReference(index, firstCell).formatAsString() + ":"
                        + new CellReference(index, lastCell).formatAsString());
            }

            Map<Object, Object> result = new LinkedHashMap<Object, Object>();
            for (int i = firstCell; i <= lastCell; i++) {
                Cell cell = row.getCell(i);
                if (cell != null) {
                    Object value = file.getCellValue(cell);
                    // dual keys for the same value
                    result.put(i, value);
                    String key = headers.get(i);
                    if (key == null) {
                        key = new CellReference(-1, i).formatAsString();
                        headers.put(i, key);
                    }
                    result.put(key, value);
                }
            }
            return result;
        }

    };

}

From source file:com.wrmsr.kleist.util.Itertools.java

public static <T> Iterator<T> lazyIterator(Supplier<? extends T> supplier) {
    return new Iterator<T>() {
        private boolean done;

        @Override//from  w ww .j a  v a2  s  . c  om
        public boolean hasNext() {
            return !done;
        }

        @Override
        public T next() {
            if (done) {
                throw new IllegalStateException();
            }
            done = true;
            return supplier.get();
        }
    };
}

From source file:org.libreplan.business.planner.limiting.entities.DateAndHour.java

/**
 * Creates an {@link Iterable} that returns a lazy iterator. If
 * <code>end</code> is <code>null</code> it will not stop and will keep on
 * producing days forever/*from w ww . j ava  2 s. c  om*/
 */
public Iterable<LocalDate> daysUntil(final DateAndHour end) {
    Validate.isTrue(end == null || end.isAfter(this));
    return new Iterable<LocalDate>() {
        @Override
        public Iterator<LocalDate> iterator() {
            return new Iterator<LocalDate>() {

                private LocalDate current = getDate();

                @Override
                public boolean hasNext() {
                    return end == null || end.isAfter(current);
                }

                @Override
                public LocalDate next() {
                    LocalDate result = current;
                    current = current.plusDays(1);
                    return result;
                }

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

From source file:org.apache.sling.discovery.impl.setup.MockedResourceResolver.java

public Iterator<Resource> listChildren(Resource parent) {
    try {/*from ww w . java 2 s .  c o  m*/
        Node node = parent.adaptTo(Node.class);
        final NodeIterator nodes = node.getNodes();
        return new Iterator<Resource>() {

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

            public Resource next() {
                Node next = nodes.nextNode();
                try {
                    return new MockedResource(MockedResourceResolver.this, next.getPath(), "nt:unstructured");
                } catch (RepositoryException e) {
                    throw new RuntimeException("RepositoryException: " + e, e);
                }
            }

            public boolean hasNext() {
                return nodes.hasNext();
            }
        };
    } catch (RepositoryException e) {
        throw new RuntimeException("RepositoryException: " + e, e);
    }
}

From source file:org.apache.apex.malhar.lib.state.spillable.SpillableSetImpl.java

@Override
public Iterator<T> iterator() {
    return new Iterator<T>() {
        T cur = head;//from  w  ww .j a  va2 s.  c o  m
        T prev = null;

        @Override
        public boolean hasNext() {
            while (cur != null) {
                ListNode<T> node = map.get(cur);
                if (node.valid) {
                    return true;
                }
                if (cur.equals(node.next)) {
                    break;
                } else {
                    cur = node.next;
                }
            }
            return false;
        }

        @Override
        public T next() {
            while (cur != null) {
                ListNode<T> node = map.get(cur);
                try {
                    if (node.valid) {
                        prev = cur;
                        return prev;
                    }
                } finally {
                    if (cur.equals(node.next)) {
                        cur = null;
                    } else {
                        cur = node.next;
                    }
                }
            }
            throw new NoSuchElementException();
        }

        @Override
        public void remove() {
            ListNode<T> node = map.get(prev);
            node.valid = false;
            map.put(prev, node);
            size--;
        }
    };
}