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.datasayer.meerkat.MeerJobRunner.java

@SuppressWarnings("unchecked")
@Override//  w w w .jav a  2s.  c  o m
public void bsp(final BSPPeer<Writable, Writable, Writable, Writable, Writable> peer)
        throws IOException, SyncException, InterruptedException {

    while (true) {
        try {
            long currentTime = System.currentTimeMillis();
            FileSystem fs = FileSystem.get(conf);
            if (!fs.isFile(logPath)) {
                System.out.println("can not read input file");
                return;
            }
            RandomAccessFile file = new RandomAccessFile(logPath.toString(), "r");
            long fileLength = file.length();

            if (fileLength > filePointer) {
                file.seek(filePointer);
                String line = null;
                while (file.length() > file.getFilePointer()) {
                    line = file.readLine();
                    line = new String(line.getBytes("8859_1"), "utf-8");
                    guardMeer.observe(line);
                }
                filePointer = file.getFilePointer();
            } else {
                // nothing to do
            }
            file.close();

            long timeDiff = currentTime - this.lastAggregatedTime;
            if (timeDiff >= this.aggregationInterval) {

                peer.sync();

                if (peer.getPeerName().equals(masterName)) {
                    bossMeer.masterCompute(new Iterator<Writable>() {

                        private final int producedMessages = peer.getNumCurrentMessages();
                        private int consumedMessages = 0;

                        @Override
                        public boolean hasNext() {
                            return producedMessages > consumedMessages;
                        }

                        @Override
                        public Writable next() throws NoSuchElementException {
                            if (consumedMessages >= producedMessages) {
                                throw new NoSuchElementException();
                            }

                            try {
                                consumedMessages++;
                                return peer.getCurrentMessage();
                            } catch (IOException e) {
                                throw new NoSuchElementException();
                            }
                        }

                        @Override
                        public void remove() {
                            // BSPPeer.getCurrentMessage originally deletes a message.
                            // Thus, it doesn't need to throw exception.
                            // throw new UnsupportedOperationException();
                        }

                    }, signalMeer);
                    this.lastAggregatedTime = currentTime;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.apache.hadoop.hbase.io.encoding.EncodedDataBlock.java

/**
 * Provides access to compressed value./*from   w w w .  j a  v  a 2 s  .  c  o  m*/
 * @param headerSize header size of the block.
 * @return Forwards sequential iterator.
 */
public Iterator<Cell> getIterator(int headerSize) {
    final int rawSize = rawKVs.length;
    byte[] encodedDataWithHeader = getEncodedData();
    int bytesToSkip = headerSize + Bytes.SIZEOF_SHORT;
    ByteArrayInputStream bais = new ByteArrayInputStream(encodedDataWithHeader, bytesToSkip,
            encodedDataWithHeader.length - bytesToSkip);
    final DataInputStream dis = new DataInputStream(bais);

    return new Iterator<Cell>() {
        private ByteBuffer decompressedData = null;

        @Override
        public boolean hasNext() {
            if (decompressedData == null) {
                return rawSize > 0;
            }
            return decompressedData.hasRemaining();
        }

        @Override
        public Cell next() {
            if (decompressedData == null) {
                try {
                    decompressedData = dataBlockEncoder.decodeKeyValues(dis,
                            dataBlockEncoder.newDataBlockDecodingContext(meta));
                } catch (IOException e) {
                    throw new RuntimeException("Problem with data block encoder, "
                            + "most likely it requested more bytes than are available.", e);
                }
                decompressedData.rewind();
            }
            int offset = decompressedData.position();
            int klen = decompressedData.getInt();
            int vlen = decompressedData.getInt();
            short tagsLen = 0;
            ByteBufferUtils.skip(decompressedData, klen + vlen);
            // Read the tag length in case when steam contain tags
            if (meta.isIncludesTags()) {
                tagsLen = decompressedData.getShort();
                ByteBufferUtils.skip(decompressedData, tagsLen);
            }
            KeyValue kv = new KeyValue(decompressedData.array(), offset,
                    (int) KeyValue.getKeyValueDataStructureSize(klen, vlen, tagsLen));
            if (meta.isIncludesMvcc()) {
                long mvccVersion = ByteBufferUtils.readVLong(decompressedData);
                kv.setMvccVersion(mvccVersion);
            }
            return kv;
        }

        @Override
        public void remove() {
            throw new NotImplementedException("remove() is not supported!");
        }

        @Override
        public String toString() {
            return "Iterator of: " + dataBlockEncoder.getClass().getName();
        }

    };
}

From source file:com.android.messaging.datamodel.data.ConversationParticipantsData.java

@Override
public Iterator<ParticipantData> iterator() {
    return new Iterator<ParticipantData>() {
        private int mCurrentIndex = -1;

        @Override//from w  w  w  . j  av  a2s . co  m
        public boolean hasNext() {
            return mCurrentIndex < mConversationParticipantsMap.size() - 1;
        }

        @Override
        public ParticipantData next() {
            mCurrentIndex++;
            if (mCurrentIndex >= mConversationParticipantsMap.size()) {
                throw new NoSuchElementException();
            }
            return mConversationParticipantsMap.valueAt(mCurrentIndex);
        }

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

From source file:org.jboss.dashboard.ui.taglib.formatter.ForFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    log.debug("Servicing ForFormatter.");
    Object array = getParameter("array");
    if (array == null) {
        Object componentName = getParameter("factoryElement");
        Object propertyName = getParameter("property");
        if (componentName != null) {
            Object component = Factory.lookup((String) componentName);
            array = component;/* ww w.  jav a2  s  .  c o m*/
            if (propertyName != null) {
                JXPathContext ctx = JXPathContext.newContext(component);
                try {
                    array = ctx.getValue((String) propertyName);
                } catch (Exception e) {
                    log.debug("Error:", e);
                }
            }
        }
    }
    String sortProperties = (String) getParameter("sortProperties");

    Iterator iterator = null;
    if (array == null) {
        renderFragment("empty");
        return;
    }

    if (array instanceof Collection) {
        iterator = ((Collection) array).iterator();
    } else if (array.getClass().isArray()) {
        final Object theArray = array;
        iterator = new Iterator() {
            int index = 0;

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

            public boolean hasNext() {
                return Array.getLength(theArray) > index;
            }

            public Object next() {
                return Array.get(theArray, index++);
            }
        };
    } else if (array instanceof Iterator) {
        iterator = (Iterator) array;
    } else if (array instanceof Enumeration) {
        List l = new ArrayList();
        while (((Enumeration) array).hasMoreElements()) {
            l.add(((Enumeration) array).nextElement());
        }
        iterator = l.iterator();
    }

    if (sortProperties != null) {
        iterator = getSortedIterator(iterator, sortProperties);
    }

    if (iterator != null && iterator.hasNext()) {
        renderFragment("outputStart");
        int i = 0;
        while (iterator.hasNext()) {
            Object o = iterator.next();
            setAttribute("index", new Integer(i));
            setAttribute("count", new Integer(++i));
            if (o != null)
                setAttribute("element", o);
            else
                setAttribute("element", getParameter("nullValue"));
            renderFragment("output");
        }
        renderFragment("outputEnd");
    } else {
        renderFragment("empty");
    }
}

From source file:de.speexx.csv.table.CsvReader.java

@Override
public Iterator<Row> iterator() {
    return new Iterator<Row>() {
        @Override/*from ww  w  .  j  a va  2 s .com*/
        public boolean hasNext() {
            return CsvReader.this.itr.hasNext();
        }

        @Override
        public Row next() {
            final CSVRecord record = CsvReader.this.itr.next();
            final List<Entry> entries = new ArrayList<>();

            CsvReader.this.descriptors.stream().forEach((desc) -> {
                final String value = record.get(desc.getName());
                final SimpleEntry<String> entry = new SimpleEntry<>(value, desc);
                entries.add(entry);
            });

            return new SimpleRow(entries);
        }
    };
}

From source file:com.px100systems.util.CsvParser.java

/**
 * Parsing into a list of maps of fields (requires header)
 *
 * @param is imput stream/*from w  w w. ja v a2  s.c  om*/
 * @return List of maps of {field, value} pairs
 */
public Iterator<Map<String, String>> parseAsMap(InputStream is) {
    final CSVParser parser = new CSVParser(new BufferedReader(new InputStreamReader(is)), csvStrategy);
    try {
        header = parser.getLine();
        return new Iterator<Map<String, String>>() {
            @Override
            public boolean hasNext() {
                try {
                    currentLine = parser.getLine();
                    return currentLine != null;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public Map<String, String> next() {
                Map<String, String> row = new HashMap<String, String>();
                for (int i = 0; i < header.length; i++)
                    row.put(header[i], currentLine[i]);
                return row;
            }
        };
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:FileSerializeCollection.java

public Iterator<Type> iterator() {
    try {//  w  w w .  ja  v  a 2  s  .  c o  m
        oos.flush();
        return new Iterator<Type>() {

            private Type next = null;

            private final ObjectInputStream ois = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(file)));

            @SuppressWarnings("unchecked")
            public boolean hasNext() {
                try {
                    if (next == null) {
                        next = (Type) ois.readObject();
                    }
                } catch (final EOFException eof) {
                    // do not report exception
                } catch (final Exception e) {
                    System.err.println(e);
                }

                try {
                    if (next == null) {
                        ois.close();
                    }
                } catch (final IOException io) {
                    System.err.println(io);
                }

                return (next != null);
            }

            public Type next() {
                if (hasNext()) {
                    final Type ret = next;
                    next = null;
                    return ret;
                }
                throw new NoSuchElementException("No more elements");
            }

            public void remove() {
                throw new UnsupportedOperationException("remove not supported in DumpSet$iterator()");
            }
        };
    } catch (final IOException io) {
        System.err.println(io);
    }
    return null;
}

From source file:org.apache.sling.nosql.generic.simple.provider.SimpleNoSqlAdapter.java

public Iterator<NoSqlData> query(String query, String language) {
    // implement simple dummy query
    if (StringUtils.equals(language, "simple") && StringUtils.equals(query, "all")) {
        final Iterator<Entry<String, Map<String, Object>>> entries = store.entrySet().iterator();
        return new Iterator<NoSqlData>() {
            public boolean hasNext() {
                return entries.hasNext();
            }/*from w w w  .j  a  v a  2 s.  c o  m*/

            public NoSqlData next() {
                Entry<String, Map<String, Object>> entry = entries.next();
                return new NoSqlData(entry.getKey(), entry.getValue());
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }
    return Collections.<NoSqlData>emptyList().iterator();
}

From source file:org.jboss.dashboard.ui.formatters.ForFormatter.java

public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException {
    log.debug("Servicing ForFormatter.");
    Object array = getParameter("array");
    if (array == null) {
        Object componentName = getParameter("factoryElement");
        Object propertyName = getParameter("property");
        if (componentName != null) {
            Object component = CDIBeanLocator.getBeanByNameOrType((String) componentName);
            array = component;//from  ww  w .j  a v a 2s .c  o m
            if (propertyName != null) {
                JXPathContext ctx = JXPathContext.newContext(component);
                try {
                    array = ctx.getValue((String) propertyName);
                } catch (Exception e) {
                    log.debug("Error:", e);
                }
            }
        }
    }
    String sortProperties = (String) getParameter("sortProperties");

    Iterator iterator = null;
    if (array == null) {
        renderFragment("empty");
        return;
    }

    if (array instanceof Collection) {
        iterator = ((Collection) array).iterator();
    } else if (array.getClass().isArray()) {
        final Object theArray = array;
        iterator = new Iterator() {
            int index = 0;

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

            public boolean hasNext() {
                return Array.getLength(theArray) > index;
            }

            public Object next() {
                return Array.get(theArray, index++);
            }
        };
    } else if (array instanceof Iterator) {
        iterator = (Iterator) array;
    } else if (array instanceof Enumeration) {
        List l = new ArrayList();
        while (((Enumeration) array).hasMoreElements()) {
            l.add(((Enumeration) array).nextElement());
        }
        iterator = l.iterator();
    }

    if (sortProperties != null) {
        iterator = getSortedIterator(iterator, sortProperties);
    }

    if (iterator != null && iterator.hasNext()) {
        renderFragment("outputStart");
        int i = 0;
        while (iterator.hasNext()) {
            Object o = iterator.next();
            setAttribute("index", new Integer(i));
            setAttribute("count", new Integer(++i));
            if (o != null)
                setAttribute("element", o);
            else
                setAttribute("element", getParameter("nullValue"));
            renderFragment("output");
        }
        renderFragment("outputEnd");
    } else {
        renderFragment("empty");
    }
}

From source file:jetbrains.exodus.util.BackupBean.java

@Override
public BackupStrategy getBackupStrategy() {
    final int targetsCount = targets.length;
    final BackupStrategy[] wrapped = new BackupStrategy[targetsCount];
    for (int i = 0; i < targetsCount; i++) {
        wrapped[i] = targets[i].getBackupStrategy();
    }//  ww  w  .j av  a  2s  .  com
    return new BackupStrategy() {
        @Override
        public void beforeBackup() throws Exception {
            backupStartTicks = System.currentTimeMillis();
            log.info("Backing up database...");
            for (final BackupStrategy strategy : wrapped) {
                strategy.beforeBackup();
            }
        }

        @Override
        public Iterable<FileDescriptor> listFiles() {
            return new Iterable<FileDescriptor>() {
                @Override
                public Iterator<FileDescriptor> iterator() {
                    return new Iterator<FileDescriptor>() {

                        @Nullable
                        private FileDescriptor next = null;
                        private int i = 0;
                        @NotNull
                        private Iterator<FileDescriptor> it = EMPTY.listFiles().iterator();

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

                        @Override
                        public FileDescriptor next() {
                            try {
                                return getNext();
                            } finally {
                                next = null;
                            }
                        }

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

                        private FileDescriptor getNext() {
                            if (next == null) {
                                while (!it.hasNext()) {
                                    if (i >= targetsCount) {
                                        return next;
                                    }
                                    it = wrapped[i++].listFiles().iterator();
                                }
                                next = it.next();
                            }
                            return next;
                        }
                    };
                }
            };
        }

        @Override
        public void afterBackup() throws Exception {
            try {
                for (final BackupStrategy strategy : wrapped) {
                    strategy.afterBackup();
                }
            } finally {
                backupStartTicks = 0;
            }
            if (commandAfterBackup != null) {
                log.info("Executing \"" + commandAfterBackup + "\"...");
                //noinspection CallToRuntimeExecWithNonConstantString,CallToRuntimeExec
                Runtime.getRuntime().exec(commandAfterBackup);
            }
            log.info("Backup finished.");
        }

        @Override
        public void onError(Throwable t) {
            backupException = t;
        }
    };
}