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:co.paralleluniverse.galaxy.core.BackupImpl.java

@Override
public Iterator<BACKUP> iterOwned() {
    final Iterator<Cache.CacheLine> it = cache.ownedIterator();
    return new Iterator<BACKUP>() {
        @Override//  w w  w .ja v  a  2s  .  c o m
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        public BACKUP next() {
            final Cache.CacheLine line = it.next();
            synchronized (line) {
                monitor.addReplicationBackup(1);
                return (BACKUP) Message.BACKUP(line.getId(), line.getVersion(), line.getData())
                        .cloneDataBuffers();
            }
        }

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

From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java

protected <T> Collection<T> getDimension(final Collection<DimensionBean> beans, final DimBeanExec<T> ctr) {
    return new AbstractCollection<T>() {

        @Override/*from   www  .ja  v a 2  s.  com*/
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                private Iterator<DimensionBean> beanIt = beans.iterator();

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

                @Override
                public T next() {
                    return ctr.exec(beanIt.next());
                }

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

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

From source file:org.apache.solr.handler.dataimport.XPathEntityProcessor.java

private Iterator<Map<String, Object>> getRowIterator(final Reader data, final String s) {
    //nothing atomic about it. I just needed a StongReference
    final AtomicReference<Exception> exp = new AtomicReference<>();
    final BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<>(blockingQueueSize);
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    final AtomicBoolean throwExp = new AtomicBoolean(true);
    publisherThread = new Thread() {
        @Override/*from   w  w w . j  ava  2 s .c  o  m*/
        public void run() {
            try {
                xpathReader.streamRecords(data, (record, xpath) -> {
                    if (isEnd.get()) {
                        throwExp.set(false);
                        //To end the streaming . otherwise the parsing will go on forever
                        //though consumer has gone away
                        throw new RuntimeException("BREAK");
                    }
                    Map<String, Object> row;
                    try {
                        row = readRow(record, xpath);
                    } catch (Exception e) {
                        isEnd.set(true);
                        return;
                    }
                    offer(row);
                });
            } catch (Exception e) {
                if (throwExp.get())
                    exp.set(e);
            } finally {
                closeIt(data);
                if (!isEnd.get()) {
                    offer(END_MARKER);
                }
            }
        }

        private void offer(Map<String, Object> row) {
            try {
                while (!blockingQueue.offer(row, blockingQueueTimeOut, blockingQueueTimeOutUnits)) {
                    if (isEnd.get())
                        return;
                    LOG.debug("Timeout elapsed writing records.  Perhaps buffer size should be increased.");
                }
            } catch (InterruptedException e) {
                return;
            } finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        }
    };

    publisherThread.start();

    return new Iterator<Map<String, Object>>() {
        private Map<String, Object> lastRow;
        int count = 0;

        @Override
        public boolean hasNext() {
            return !isEnd.get();
        }

        @Override
        public Map<String, Object> next() {
            Map<String, Object> row;

            do {
                try {
                    row = blockingQueue.poll(blockingQueueTimeOut, blockingQueueTimeOutUnits);
                    if (row == null) {
                        LOG.debug("Timeout elapsed reading records.");
                    }
                } catch (InterruptedException e) {
                    LOG.debug("Caught InterruptedException while waiting for row.  Aborting.");
                    isEnd.set(true);
                    return null;
                }
            } while (row == null);

            if (row == END_MARKER) {
                isEnd.set(true);
                if (exp.get() != null) {
                    String msg = "Parsing failed for xml, url:" + s + " rows processed in this xml:" + count;
                    if (lastRow != null)
                        msg += " last row in this xml:" + lastRow;
                    if (ABORT.equals(onError)) {
                        wrapAndThrow(SEVERE, exp.get(), msg);
                    } else if (SKIP.equals(onError)) {
                        wrapAndThrow(DataImportHandlerException.SKIP, exp.get());
                    } else {
                        LOG.warn(msg, exp.get());
                    }
                }
                return null;
            }
            count++;
            return lastRow = row;
        }

        @Override
        public void remove() {
            /*no op*/
        }
    };

}

From source file:org.languagetool.AnalyzedTokenReadings.java

/**
 * @since 2.3// w  w w  .j  ava2  s  .co  m
 */
@Override
public Iterator<AnalyzedToken> iterator() {
    AtomicInteger i = new AtomicInteger(0);
    return new Iterator<AnalyzedToken>() {
        @Override
        public boolean hasNext() {
            return i.get() < getReadingsLength();
        }

        @Override
        public AnalyzedToken next() {
            try {
                return anTokReadings[i.getAndAdd(1)];
            } catch (ArrayIndexOutOfBoundsException e) {
                throw new NoSuchElementException(
                        "No such element: " + i + ", element count: " + anTokReadings.length);
            }
        }

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

From source file:com.hs.mail.mailet.RemoteDelivery.java

private static Iterator<HostAddress> getGatewaySmtpHostAddresses(final String gateway) {
    return new Iterator<HostAddress>() {
        private Iterator<HostAddress> addresses = null;

        public boolean hasNext() {
            if (addresses == null) {
                String server = gateway;
                String port = "25";

                int idx = server.indexOf(':');
                if (idx > 0) {
                    port = server.substring(idx + 1);
                    server = server.substring(0, idx);
                }//from   w ww .j  a  v a  2s.c  om

                final String nextGateway = server;
                final String nextGatewayPort = port;
                try {
                    final InetAddress[] ips = DnsServer.getAllByName(nextGateway);
                    addresses = new Iterator<HostAddress>() {
                        private InetAddress[] ipAddresses = ips;
                        int i = 0;

                        public boolean hasNext() {
                            return i < ipAddresses.length;
                        }

                        public HostAddress next() {
                            return new HostAddress(nextGateway,
                                    "smtp://" + (ipAddresses[i++]).getHostAddress() + ":" + nextGatewayPort);
                        }

                        public void remove() {
                            throw new UnsupportedOperationException("remove not supported by this iterator");
                        }
                    };
                } catch (UnknownHostException uhe) {
                    logger.error("Unknown gateway host: " + uhe.getMessage().trim());
                    logger.error("This could be a DNS server error or configuration error.");
                }
            }
            return addresses != null && addresses.hasNext();
        }

        public HostAddress next() {
            return addresses != null ? addresses.next() : null;
        }

        public void remove() {
            throw new UnsupportedOperationException("remove not supported by this iterator");
        }
    };
}

From source file:edu.byu.nlp.crowdsourcing.models.gibbs.BlockCollapsedMultiAnnModelMath.java

public static Iterable<Prediction> predictions(final Dataset data, final int y[],
        final Map<String, Integer> instanceMap) {
    return new Iterable<Prediction>() {

        @Override//  w  ww .j  a v a  2  s  . c  o m
        public Iterator<Prediction> iterator() {
            return new Iterator<Prediction>() {

                // only predict on unlabeled portion of dataset; the labeled portion is known
                private Iterator<DatasetInstance> it = data.iterator();

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

                @Override
                public Prediction next() {
                    DatasetInstance instance = it.next();
                    // prediction based on most recent sample
                    Integer prediction = null;
                    if (instanceMap.containsKey(instance.getInfo().getRawSource())) {
                        prediction = y[instanceMap.get(instance.getInfo().getRawSource())];
                    }
                    return new BasicPrediction(prediction, instance);
                }

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

From source file:com.github.jsonj.JsonArray.java

/**
 * Convenience method to prevent casting JsonElement to JsonArray when iterating in the common case that you have
 * an array of JsonArrays./*from w  w  w  . j av a2 s .co  m*/
 *
 * @return iterable that iterates over JsonArrays instead of JsonElements.
 */
public Iterable<JsonArray> arrays() {
    final JsonArray parent = this;
    return new Iterable<JsonArray>() {

        @Override
        public Iterator<JsonArray> iterator() {
            final Iterator<JsonElement> iterator = parent.iterator();
            return new Iterator<JsonArray>() {

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

                @Override
                public JsonArray next() {
                    return iterator.next().asArray();
                }

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

From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java

protected <T> Collection<T> getAccumulation(final Collection<DimensionBean> beans, final DimBeanExec<T> ctr) {
    return new AbstractCollection<T>() {

        @Override//ww w.  j  av a2s . c  o  m
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                private Iterator<DimensionBean> beanIt = beans.iterator();

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

                @Override
                public T next() {
                    return ctr.exec(beanIt.next());
                }

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

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

From source file:gobblin.couchbase.writer.CouchbaseWriterTest.java

@Test
public void testMultiTupleDocumentWrite()
        throws IOException, DataConversionException, ExecutionException, InterruptedException {
    CouchbaseWriter writer = new CouchbaseWriter(_couchbaseEnvironment, ConfigFactory.empty());
    try {// w w  w.jav  a2  s. com

        final Schema dataRecordSchema = SchemaBuilder.record("Data").fields().name("data").type().bytesType()
                .noDefault().name("flags").type().intType().noDefault().endRecord();

        final Schema schema = SchemaBuilder.record("TestRecord").fields().name("key").type().stringType()
                .noDefault().name("data").type(dataRecordSchema).noDefault().endRecord();

        final int numRecords = 1000;
        int outstandingRequests = 99;

        Iterator<GenericRecord> recordIterator = new Iterator<GenericRecord>() {
            private int currentIndex;

            @Override
            public void remove() {
            }

            @Override
            public boolean hasNext() {
                return (currentIndex < numRecords);
            }

            @Override
            public GenericRecord next() {
                GenericData.Record testRecord = new GenericData.Record(schema);

                String testContent = "hello world" + currentIndex;
                GenericData.Record dataRecord = new GenericData.Record(dataRecordSchema);
                dataRecord.put("data", ByteBuffer.wrap(testContent.getBytes(Charset.forName("UTF-8"))));
                dataRecord.put("flags", 0);

                testRecord.put("key", "hello" + currentIndex);
                testRecord.put("data", dataRecord);
                currentIndex++;
                return testRecord;
            }
        };

        long kvTimeout = 10000;
        TimeUnit kvTimeoutUnit = TimeUnit.MILLISECONDS;
        writeRecords(new TupleDocumentIterator(recordIterator), writer, outstandingRequests, kvTimeout,
                kvTimeoutUnit);
    } finally {
        writer.close();
    }
}

From source file:org.apache.solr.handler.dataimport.processor.XPathEntityProcessor.java

private Iterator<Map<String, Object>> getRowIterator(final Reader data, final String s) {
    //nothing atomic about it. I just needed a StongReference
    final AtomicReference<Exception> exp = new AtomicReference<Exception>();
    final BlockingQueue<Map<String, Object>> blockingQueue = new ArrayBlockingQueue<Map<String, Object>>(
            blockingQueueSize);/* w w  w  .  j  a  va 2 s  . co  m*/
    final AtomicBoolean isEnd = new AtomicBoolean(false);
    final AtomicBoolean throwExp = new AtomicBoolean(true);
    publisherThread = new Thread() {
        @Override
        public void run() {
            try {
                xpathReader.streamRecords(data, new XPathRecordReader.Handler() {
                    @Override
                    @SuppressWarnings("unchecked")
                    public void handle(Map<String, Object> record, String xpath) {
                        if (isEnd.get()) {
                            throwExp.set(false);
                            //To end the streaming . otherwise the parsing will go on forever
                            //though consumer has gone away
                            throw new RuntimeException("BREAK");
                        }
                        Map<String, Object> row;
                        try {
                            row = readRow(record, xpath);
                        } catch (final Exception e) {
                            isEnd.set(true);
                            return;
                        }
                        offer(row);
                    }
                });
            } catch (final Exception e) {
                if (throwExp.get())
                    exp.set(e);
            } finally {
                closeIt(data);
                if (!isEnd.get()) {
                    offer(END_MARKER);
                }
            }
        }

        private void offer(Map<String, Object> row) {
            try {
                while (!blockingQueue.offer(row, blockingQueueTimeOut, blockingQueueTimeOutUnits)) {
                    if (isEnd.get())
                        return;
                    LOG.debug("Timeout elapsed writing records.  Perhaps buffer size should be increased.");
                }
            } catch (final InterruptedException e) {
                return;
            } finally {
                synchronized (this) {
                    notifyAll();
                }
            }
        }
    };

    publisherThread.start();

    return new Iterator<Map<String, Object>>() {
        private Map<String, Object> lastRow;
        int count = 0;

        @Override
        public boolean hasNext() {
            return !isEnd.get();
        }

        @Override
        public Map<String, Object> next() {
            Map<String, Object> row;

            do {
                try {
                    row = blockingQueue.poll(blockingQueueTimeOut, blockingQueueTimeOutUnits);
                    if (row == null) {
                        LOG.debug("Timeout elapsed reading records.");
                    }
                } catch (final InterruptedException e) {
                    LOG.debug("Caught InterruptedException while waiting for row.  Aborting.");
                    isEnd.set(true);
                    return null;
                }
            } while (row == null);

            if (row == END_MARKER) {
                isEnd.set(true);
                if (exp.get() != null) {
                    String msg = "Parsing failed for xml, url:" + s + " rows processed in this xml:" + count;
                    if (lastRow != null)
                        msg += " last row in this xml:" + lastRow;
                    if (ABORT.equals(onError)) {
                        wrapAndThrow(SEVERE, exp.get(), msg);
                    } else if (SKIP.equals(onError)) {
                        wrapAndThrow(DataImportHandlerException.SKIP, exp.get());
                    } else {
                        LOG.warn(msg, exp.get());
                    }
                }
                return null;
            }
            count++;
            return lastRow = row;
        }

        @Override
        public void remove() {
            /*no op*/
        }
    };

}