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:org.normandra.cassandra.CassandraDatabaseQuery.java

@Override
public Iterator<T> iterator() {
    return new Iterator<T>() {
        @Override// w  w w.jav a2 s  . c  o  m
        public boolean hasNext() {
            return !ensurResults().isExhausted();
        }

        @Override
        public T next() {
            final Row row = ensurResults().one();
            if (null == row) {
                return null;
            }
            rows.add(row);
            try {
                return build(row);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Unable to get next entity [" + entity + "] from row [" + row + "].", e);
            }
        }
    };
}

From source file:com.hs.mail.dns.DnsServer.java

public Iterator<HostAddress> getSmtpHostAddress(final String domainName) {
    return new Iterator<HostAddress>() {
        private Iterator<String> mxHosts = findMXRecords(domainName).iterator();
        private Iterator<HostAddress> addresses = null;

        public boolean hasNext() {
            /*//from   w w w.j a v  a 2  s. c o m
             * Make sure that when next() is called, that we can provide a
             * HostAddress. This means that we need to have an inner
             * iterator, and verify that it has addresses. We could, for
             * example, run into a situation where the next mxHost didn't
             * have any valid addresses.
             */
            if ((addresses == null || !addresses.hasNext()) && mxHosts.hasNext()) {
                do {
                    final String nextHostname = (String) mxHosts.next();
                    InetAddress[] addrs = null;
                    try {
                        addrs = getAllByName(nextHostname);
                    } catch (UnknownHostException e) {
                        // this should never happen, since we just got
                        // this host from mxHosts, which should have
                        // already done this check.
                        StringBuffer logBuffer = new StringBuffer(128)
                                .append("Couldn't resolve IP address for discovered host ").append(nextHostname)
                                .append(".");
                        logger.error(logBuffer.toString());
                    }

                    final InetAddress[] ipAddresses = addrs;
                    addresses = new Iterator<HostAddress>() {
                        int i = 0;

                        public boolean hasNext() {
                            return ipAddresses != null && i < ipAddresses.length;
                        }

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

                        public void remove() {
                            throw new UnsupportedOperationException("remove not supported by this iterator");
                        }
                    };
                } while (!addresses.hasNext() && mxHosts.hasNext());
            }
            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:org.onehippo.forge.exdocpicker.impl.field.ExternalDocumentFieldSelectorPlugin.java

private RefreshingView createCompareView(final ExternalDocumentCollection<Serializable> docCollection,
        final ExternalDocumentCollection<Serializable> baseDocCollection) {

    return new RefreshingView("view") {

        @Override//from w w  w. jav a  2  s . com
        protected Iterator getItemModels() {
            Serializable[] baseDocs = baseDocCollection.toArray(new Serializable[baseDocCollection.getSize()]);
            Serializable[] currentDocs = docCollection.toArray(new Serializable[docCollection.getSize()]);

            List<Change<Serializable>> changeSet = LCS.getChangeSet(baseDocs, currentDocs);
            final Change<Serializable>[] changes = changeSet.toArray(new Change[changeSet.size()]);

            return new Iterator<IModel<Change<? extends Serializable>>>() {

                private int changeSetIndex = 0;

                public boolean hasNext() {
                    return changeSetIndex < changes.length;
                }

                public IModel<Change<? extends Serializable>> next() {

                    if (changeSetIndex >= changes.length) {
                        throw new NoSuchElementException();
                    }

                    final Change<? extends Serializable> change = changes[changeSetIndex++];

                    return new Model<Change<? extends Serializable>>(change);
                }

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

        @Override
        protected void populateItem(Item item) {
            Change<? extends Serializable> change = (Change<? extends Serializable>) item.getModelObject();
            final Serializable searchDoc = change.getValue();

            final Label label = new Label("link-text", new Model<String>() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    return getExternalDocumentServiceFacade().getDocumentTitle(
                            getExternalDocumentServiceContext(), searchDoc, getRequest().getLocale());
                }
            });

            final String description = getExternalDocumentServiceFacade().getDocumentDescription(
                    getExternalDocumentServiceContext(), searchDoc, getRequest().getLocale());
            if (StringUtils.isNotBlank(description)) {
                label.add(new AttributeModifier("title", description));
            }

            if (change.getType() == ChangeType.ADDED) {
                label.add(new AttributeAppender("class", new Model("hippo-diff-added"), " "));
            } else if (change.getType() == ChangeType.REMOVED) {
                label.add(new AttributeAppender("class", new Model("hippo-diff-removed"), " "));
            }

            item.add(label);

            addControlsToListItem(docCollection, item);
        }
    };
}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Return an iterator on the GeoTimeSerie ticks.
 * //from   ww  w  .j a  v a2 s  . com
 * If the GTS is bucketized, one tick per bucket is returned,
 * otherwise only the ticks for which there are values are returned.
 * 
 * If the GTS is not bucketized, the ticks are first sorted in natural ordering.
 * There is no tick deduplication.
 * 
 * 
 * @param gts GeoTimeSerie instance for which to return an iterator
 * @param reversed If true, ticks will be returned from most recent to oldest
 * @return
 */
public static final Iterator<Long> tickIterator(GeoTimeSerie gts, final boolean reversed) {
    final GeoTimeSerie itergts = gts;

    if (!isBucketized(gts)) {

        //
        // GTS is not bucketized, return the ticks
        //

        sort(gts, false);

        return new Iterator<Long>() {

            int idx = reversed ? itergts.values - 1 : 0;

            @Override
            public boolean hasNext() {
                return reversed ? (idx > 0) : (idx < itergts.values);
            }

            @Override
            public Long next() {
                return itergts.ticks[reversed ? idx-- : idx++];
            };

            @Override
            public void remove() {
                // NOOP          
            }
        };
    } else {

        //
        // GTS is bucketized
        //

        return new Iterator<Long>() {
            long bucket = reversed ? 0 : itergts.bucketcount - 1;

            @Override
            public boolean hasNext() {
                return reversed ? bucket < itergts.bucketcount : bucket >= 0;
            }

            @Override
            public Long next() {
                long ts = itergts.lastbucket - bucket * itergts.bucketspan;

                if (reversed) {
                    bucket++;
                } else {
                    bucket--;
                }

                return ts;
            }

            @Override
            public void remove() {
                // NOOP          
            }
        };
    }
}

From source file:org.gdms.driver.csv.CSVDriver.java

@Override
public Iterator<Value[]> iterator() {
    if (rows == null) {
        try {//from   w  w w  . ja v a 2s  . co m
            return new CSVIterator();
        } catch (DriverException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        return new Iterator<Value[]>() {

            private Iterator<String[]> it = rows.iterator();

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

            @Override
            public Value[] next() {
                String[] next = it.next();
                Value[] v = new Value[next.length];
                for (int i = 0; i < next.length; i++) {
                    v[i] = createValue(next[i]);
                }
                return v;
            }

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

From source file:net.metanotion.web.servlets.SimpleRequestObject.java

@Override
public Iterable<String> getHeaders() {
    return new Iterable<String>() {
        @Override/*ww  w .  j ava2s .c o m*/
        public Iterator<String> iterator() {
            final Enumeration<String> e = req.getHeaderNames();
            if (e == null) {
                return new Iterator<String>() {
                    @Override
                    public boolean hasNext() {
                        return false;
                    }

                    @Override
                    public String next() {
                        throw new java.util.NoSuchElementException();
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            } else {
                return new Iterator<String>() {
                    @Override
                    public boolean hasNext() {
                        return e.hasMoreElements();
                    }

                    @Override
                    public String next() {
                        return e.nextElement();
                    }

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

From source file:org.deidentifier.arx.aggregates.StatisticsBuilder.java

/**
 * Returns a contingency table for the given columns. The order for string data items is derived
 * from the provided hierarchies//w ww . ja v  a2 s  . c  o  m
 * 
 * @param column1 The first column
 * @param hierarchy1 The hierarchy for the first column, may be null
 * @param column2 The second column
 * @param hierarchy2 The hierarchy for the second column, may be null
 * @return
 */
public StatisticsContingencyTable getContingencyTable(int column1, String[][] hierarchy1, int column2,
        String[][] hierarchy2) {

    // Reset stop flag
    interrupt.value = false;

    // Init
    String[] values1 = getDistinctValuesOrdered(column1, hierarchy1);
    String[] values2 = getDistinctValuesOrdered(column2, hierarchy2);

    // Create maps of indexes
    Map<String, Integer> indexes1 = new HashMap<String, Integer>();
    for (int i = 0; i < values1.length; i++) {
        checkInterrupt();
        indexes1.put(values1[i], i);
    }
    Map<String, Integer> indexes2 = new HashMap<String, Integer>();
    for (int i = 0; i < values2.length; i++) {
        checkInterrupt();
        indexes2.put(values2[i], i);
    }

    // Create entry set
    int max = Integer.MIN_VALUE;
    final Map<Entry, Integer> entries = new HashMap<Entry, Integer>();
    for (int row = 0; row < handle.getNumRows(); row++) {
        checkInterrupt();
        int index1 = indexes1.get(handle.getValue(row, column1));
        int index2 = indexes2.get(handle.getValue(row, column2));
        Entry entry = new Entry(index1, index2);
        Integer previous = entries.get(entry);
        int value = previous != null ? previous + 1 : 1;
        max = Math.max(max, value);
        entries.put(entry, value);
    }

    // Create iterator
    final int count = handle.getNumRows();
    final Iterator<Entry> internal = entries.keySet().iterator();
    final Iterator<Entry> iterator = new Iterator<Entry>() {

        private Map<Entry, Integer> _entries = entries;
        private Iterator<Entry> _internal = internal;

        @Override
        public boolean hasNext() {

            if (_internal == null)
                return false;
            boolean result = _internal.hasNext();

            // Try to release resources as early as possible
            if (!result) {
                _internal = null;
                _entries = null;
            }
            return result;
        }

        @Override
        public Entry next() {
            if (_internal == null)
                return null;
            Entry e = _internal.next();
            e.frequency = (double) _entries.get(e) / (double) count;
            return e;
        }

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

    // Result result
    return new StatisticsContingencyTable(values1, values2, count, (double) max / (double) count, iterator);
}

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

@Override
public Iterable<Double> getDoubles(String key) {
    try {/* w w w .j ava2 s.c o  m*/
        final JSONArray array = obj.getJSONArray(key);

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

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

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

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

    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}

From source file:org.apache.atlas.repository.graph.GraphHelper.java

public Iterator<AtlasEdge> getAdjacentEdgesByLabel(AtlasVertex instanceVertex, AtlasEdgeDirection direction,
        final String edgeLabel) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Finding edges for {} with label {}", string(instanceVertex), edgeLabel);
    }/*from  ww  w .  ja  v  a 2s. com*/

    if (instanceVertex != null && edgeLabel != null) {
        final Iterator<AtlasEdge> iterator = instanceVertex.getEdges(direction).iterator();
        return new Iterator<AtlasEdge>() {
            private AtlasEdge edge = null;

            @Override
            public boolean hasNext() {
                while (edge == null && iterator.hasNext()) {
                    AtlasEdge localEdge = iterator.next();
                    if (localEdge.getLabel().equals(edgeLabel)) {
                        edge = localEdge;
                    }
                }
                return edge != null;
            }

            @Override
            public AtlasEdge next() {
                if (hasNext()) {
                    AtlasEdge localEdge = edge;
                    edge = null;
                    return localEdge;
                }
                return null;
            }

            @Override
            public void remove() {
                throw new IllegalStateException("Not handled");
            }
        };
    }
    return null;
}

From source file:forge.card.CardType.java

@Override
public Iterator<String> iterator() {
    final Iterator<CoreType> coreTypeIterator = coreTypes.iterator();
    final Iterator<Supertype> supertypeIterator = supertypes.iterator();
    final Iterator<String> subtypeIterator = subtypes.iterator();
    return new Iterator<String>() {
        @Override/*from www .j a  v  a  2  s .  c  o  m*/
        public boolean hasNext() {
            return coreTypeIterator.hasNext() || supertypeIterator.hasNext() || subtypeIterator.hasNext();
        }

        @Override
        public String next() {
            if (coreTypeIterator.hasNext()) {
                return coreTypeIterator.next().name();
            }
            if (supertypeIterator.hasNext()) {
                return supertypeIterator.next().name();
            }
            return subtypeIterator.next();
        }

        @Override
        public void remove() {
            throw new NotImplementedException("Removing this way not supported");
        }
    };
}