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.apache.myfaces.context.servlet.ServletExternalContextImpl.java

public Iterator getRequestParameterNames() {
    final Enumeration enumer = _servletRequest.getParameterNames();
    Iterator it = new Iterator() {
        public boolean hasNext() {
            return enumer.hasMoreElements();
        }/*from w w  w .  j a v a2 s  .c om*/

        public Object next() {
            return enumer.nextElement();
        }

        public void remove() {
            throw new UnsupportedOperationException(
                    this.getClass().getName() + " UnsupportedOperationException");
        }
    };
    return it;
}

From source file:ArrayMap.java

/**
 * @see java.util.Map#entrySet()//ww  w.j ava2s.com
 */
public Set<Map.Entry<K, V>> entrySet() {
    final Object[] iterKeys = theKeys;
    final Object[] iterVals = theValues;
    return new java.util.AbstractSet<Map.Entry<K, V>>() {
        @Override
        public int size() {
            return iterVals.length;
        }

        @Override
        public Iterator<Map.Entry<K, V>> iterator() {
            return new Iterator<Map.Entry<K, V>>() {
                private int index = 0;

                public boolean hasNext() {
                    return index < iterVals.length;
                }

                public Map.Entry<K, V> next() {
                    final K entryKey = (K) iterKeys[index];
                    final V[] entryVal = (V[]) new Object[] { iterVals[index] };
                    Map.Entry<K, V> ret = new Map.Entry<K, V>() {
                        public K getKey() {
                            return entryKey;
                        }

                        public V getValue() {
                            return entryVal[0];
                        }

                        public V setValue(V value) {
                            ArrayMap.this.put(entryKey, value);
                            V ret2 = entryVal[0];
                            entryVal[0] = value;
                            return ret2;
                        }
                    };
                    index++;
                    return ret;
                }

                public void remove() {
                    ArrayMap.this.remove(iterKeys[index - 1]);
                }
            };
        }
    };
}

From source file:com.vaushell.superpipes.tools.scribe.twitter.TwitterClient.java

/**
 * Iterate a Twitter timeline.//from   w  w  w  . j ava  2s .  c om
 *
 * @param forcedTarget Target's ID. Could be null to use login target.
 * @param count Max tweet by call. Could be null to use default.
 * @return a tweets iterator
 */
public Iterator<TW_Tweet> iteratorTimeline(final Long forcedTarget, final Integer count) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] iteratorTimeline() : forcedTarget=" + forcedTarget
                + " / count=" + count);
    }

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

                    final String url;
                    final Properties properties = new Properties();
                    if (forcedTarget == null) {
                        url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
                    } else {
                        url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
                        properties.setProperty("user_id", Long.toString(forcedTarget));
                    }
                    if (count != null) {
                        properties.setProperty("count", Integer.toString(count));
                    }
                    if (maxID != null) {
                        properties.setProperty("max_id", Long.toString(maxID - 1L));
                    }

                    final List<TW_Tweet> tweets = readTimelineImpl(url, properties);
                    if (tweets.isEmpty()) {
                        return false;
                    } else {
                        maxID = tweets.get(tweets.size() - 1).getID();

                        buffer.addAll(tweets);

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

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

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

        // PRIVATE
        private final List<TW_Tweet> buffer = new ArrayList<>();
        private int bufferCursor;
        private Long maxID;
    };
}

From source file:InlineSchemaValidator.java

public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null) {
        throw new IllegalArgumentException("Namespace URI cannot be null.");
    } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
        return new Iterator() {
            boolean more = true;

            public boolean hasNext() {
                return more;
            }//from   w w w .j av  a 2s .  c  o  m

            public Object next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                more = false;
                return XMLConstants.XML_NS_PREFIX;
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
        return new Iterator() {
            boolean more = true;

            public boolean hasNext() {
                return more;
            }

            public Object next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                more = false;
                return XMLConstants.XMLNS_ATTRIBUTE;
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    } else if (fURIToPrefixMappings != null) {
        HashSet prefixes = (HashSet) fURIToPrefixMappings.get(namespaceURI);
        if (prefixes != null && prefixes.size() > 0) {
            return prefixes.iterator();
        }
    }
    return Collections.EMPTY_LIST.iterator();
}

From source file:org.briljantframework.data.vector.AbstractVector.java

@Override
public <T> Set<Pair<Object, T>> indexSet(Class<T> cls) {
    return new AbstractSet<Pair<Object, T>>() {
        @Override/*from w  w  w  . j ava  2  s  .c o m*/
        public Iterator<Pair<Object, T>> iterator() {
            return new Iterator<Pair<Object, T>>() {
                Iterator<Object> keys = getIndex().iterator();

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

                @Override
                public Pair<Object, T> next() {
                    Object key = keys.next();
                    return new ImmutablePair<>(key, get(cls, key));
                }
            };
        }

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

From source file:com.github.helenusdriver.commons.collections.graph.ConcurrentHashDirectedGraph.java

/**
 * {@inheritDoc}/*from  w w w.  j  av  a  2 s  .  co m*/
 *
 * @author paouelle
 *
 * @see java.util.Set#iterator()
 */
@Override
public Iterator<T> iterator() {
    final Iterator<Map.Entry<T, HashNode>> i = graph.entrySet().iterator();

    return new Iterator<T>() {
        Map.Entry<T, HashNode> current = null;

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

        @Override
        public T next() {
            this.current = i.next();
            return current.getKey();
        }

        @Override
        @SuppressWarnings("synthetic-access")
        public void remove() {
            org.apache.commons.lang3.Validate.validState(current != null);
            i.remove();
            // we need to remove all edges to the removed node
            graph.values().stream().forEach(n -> n.edges.remove(current));
            this.current = null;
        }
    };
}

From source file:org.kie.commons.java.nio.fs.file.SimpleFileSystemProvider.java

@Override
public DirectoryStream<Path> newDirectoryStream(final Path dir, final DirectoryStream.Filter<Path> filter)
        throws NotDirectoryException, IOException, SecurityException {
    checkNotNull("filter", filter);
    final File file = checkNotNull("dir", dir).toFile();

    if (!file.isDirectory()) {
        throw new NotDirectoryException(dir.toString());
    }//w w  w. j a va2 s. co m
    final File[] content = file.listFiles();

    if (content == null) {
        throw new NotDirectoryException(dir.toString());
    }

    return new DirectoryStream<Path>() {
        boolean isClosed = false;

        @Override
        public void close() throws IOException {
            if (isClosed) {
                throw new IOException();
            }
            isClosed = true;
        }

        @Override
        public Iterator<Path> iterator() {
            if (isClosed) {
                throw new IOException();
            }
            return new Iterator<Path>() {
                private int i = -1;
                private Path nextEntry = null;
                public boolean atEof = false;

                @Override
                public boolean hasNext() {
                    if (nextEntry == null && !atEof) {
                        nextEntry = readNextEntry();
                    }
                    return nextEntry != null;
                }

                @Override
                public Path next() {
                    final Path result;
                    if (nextEntry == null && !atEof) {
                        result = readNextEntry();
                    } else {
                        result = nextEntry;
                        nextEntry = null;
                    }
                    if (result == null) {
                        throw new NoSuchElementException();
                    }
                    return result;
                }

                private Path readNextEntry() {
                    if (atEof) {
                        return null;
                    }

                    Path result = null;
                    while (true) {
                        i++;
                        if (i >= content.length) {
                            atEof = true;
                            break;
                        }

                        final Path path = GeneralPathImpl.newFromFile(getDefaultFileSystem(), content[i]);
                        if (filter.accept(path)) {
                            result = path;
                            break;
                        }
                    }

                    return result;
                }

                @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  .j a v  a 2 s . co  m*/
 * 
 * @param column1 The first column
 * @param size1 The maximal size in this dimension
 * @param hierarchy1 The hierarchy for the first column, may be null
 * @param column2 The second column
 * @param size2 The maximal size in this dimension
 * @param hierarchy2 The hierarchy for the second column, may be null
 * @return
 */
public StatisticsContingencyTable getContingencyTable(int column1, int size1, String[][] hierarchy1,
        int column2, int size2, String[][] hierarchy2) {

    // Reset stop flag
    interrupt.value = false;

    // Check
    if (size1 <= 0 || size2 <= 0) {
        throw new IllegalArgumentException("Size must be > 0");
    }

    // Obtain default table
    StatisticsContingencyTable table = getContingencyTable(column1, hierarchy1, column2, hierarchy2);

    // Check if suitable
    if (table.values1.length <= size1 && table.values2.length <= size2) {
        return table;
    }

    // Init
    String[] values1;
    String[] values2;
    double factor1;
    double factor2;

    // Compute factors and values
    if (table.values1.length > size1) {
        factor1 = (double) size1 / (double) table.values1.length;
        values1 = getScaledValues(table.values1, size1);
    } else {
        factor1 = 1;
        values1 = table.values1;
    }
    if (table.values2.length > size2) {
        factor2 = (double) size2 / (double) table.values2.length;
        values2 = getScaledValues(table.values2, size2);
    } else {
        factor2 = 1;
        values2 = table.values2;
    }

    // Create entry set
    final Map<Entry, Double> entries = new HashMap<Entry, Double>();
    Iterator<Entry> iter = table.iterator;
    double max = 0d;
    while (iter.hasNext()) {
        checkInterrupt();
        Entry old = iter.next();
        int index1 = (int) Math.round((double) old.value1 * factor1);
        int index2 = (int) Math.round((double) old.value2 * factor2);
        index1 = index1 < size1 ? index1 : size1 - 1;
        index2 = index2 < size2 ? index2 : size2 - 1;
        Entry entry = new Entry(index1, index2);
        Double previous = entries.get(entry);
        double value = previous != null ? previous + old.frequency : old.frequency;
        max = Math.max(value, max);
        entries.put(entry, value);
    }

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

        private Map<Entry, Double> _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 = _entries.get(e);
            return e;
        }

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

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

From source file:org.apache.kylin.engine.spark.SparkCubing.java

private void writeDictionary(DataFrame intermediateTable, String cubeName, String segmentId) throws Exception {
    final KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
    final CubeManager cubeManager = CubeManager.getInstance(kylinConfig);
    final CubeInstance cubeInstance = cubeManager.reloadCubeLocal(cubeName);
    final String[] columns = intermediateTable.columns();
    final CubeSegment seg = cubeInstance.getSegmentById(segmentId);
    final CubeDesc cubeDesc = cubeInstance.getDescriptor();
    final HashMap<Integer, TblColRef> tblColRefMap = Maps.newHashMap();
    final CubeJoinedFlatTableEnrich flatDesc = new CubeJoinedFlatTableEnrich(
            EngineFactory.getJoinedFlatTableDesc(seg), cubeDesc);
    final List<TblColRef> baseCuboidColumn = Cuboid.findById(cubeDesc, Cuboid.getBaseCuboidId(cubeDesc))
            .getColumns();/*from  w w  w .  j a  v a 2 s .c o  m*/
    final long start = System.currentTimeMillis();
    final RowKeyDesc rowKey = cubeDesc.getRowkey();
    for (int i = 0; i < baseCuboidColumn.size(); i++) {
        TblColRef col = baseCuboidColumn.get(i);
        if (!rowKey.isUseDictionary(col)) {
            continue;
        }
        final int rowKeyColumnIndex = flatDesc.getRowKeyColumnIndexes()[i];
        tblColRefMap.put(rowKeyColumnIndex, col);
    }

    Map<TblColRef, Dictionary<String>> dictionaryMap = Maps.newHashMap();
    for (Map.Entry<Integer, TblColRef> entry : tblColRefMap.entrySet()) {
        final String column = columns[entry.getKey()];
        final TblColRef tblColRef = entry.getValue();
        final DataFrame frame = intermediateTable.select(column).distinct();

        final Row[] rows = frame.collect();
        dictionaryMap.put(tblColRef, DictionaryGenerator.buildDictionary(tblColRef.getType(),
                new IterableDictionaryValueEnumerator(new Iterable<String>() {
                    @Override
                    public Iterator<String> iterator() {
                        return new Iterator<String>() {
                            int i = 0;

                            @Override
                            public boolean hasNext() {
                                return i < rows.length;
                            }

                            @Override
                            public String next() {
                                if (hasNext()) {
                                    final Row row = rows[i++];
                                    final Object o = row.get(0);
                                    return o != null ? o.toString() : null;
                                } else {
                                    throw new NoSuchElementException();
                                }
                            }

                            @Override
                            public void remove() {
                                throw new UnsupportedOperationException();
                            }
                        };
                    }
                })));
    }
    final long end = System.currentTimeMillis();
    CubingUtils.writeDictionary(seg, dictionaryMap, start, end);
    try {
        CubeUpdate cubeBuilder = new CubeUpdate(cubeInstance);
        cubeBuilder.setToUpdateSegs(seg);
        cubeManager.updateCube(cubeBuilder);
    } catch (IOException e) {
        throw new RuntimeException("Failed to deal with the request: " + e.getLocalizedMessage());
    }
}

From source file:fr.gael.dhus.olingo.v1.Processor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  ww  . j  a va2 s .com
public ODataResponse readEntitySet(GetEntitySetUriInfo uri_info, String content_type) throws ODataException {
    // Gets values for `skip` and `top` (pagination).
    int defaultTop = CONFIGURATION_MANAGER.getOdataConfiguration().getDefaultTop();
    int skip = (uri_info.getSkip() == null) ? 0 : uri_info.getSkip();
    int top = (uri_info.getTop() == null) ? defaultTop : uri_info.getTop();

    // Gets the `collection` part of the URI.
    EdmEntitySet targetES = uri_info.getTargetEntitySet();
    AbstractEntitySet target = Model.getEntitySet(targetES.getName());
    boolean is_navlink = !uri_info.getNavigationSegments().isEmpty();

    // Validity and security checks.
    if (!target.isAuthorized(Security.getCurrentUser()) || !is_navlink && !target.isTopLevel()) {
        throw new NotAllowedException();
    }

    // Contained target workaround (non OData2: non standard!)
    if (is_navlink) {
        int last_id = getContext().getPathInfo().getODataSegments().size() - 1;
        String navlinkname = getContext().getPathInfo().getODataSegments().get(last_id).getPath();
        if (!navlinkname.equals(targetES.getName())) {
            targetES = new ContainedEntitySetDecorator(navlinkname, targetES);
        }
    }

    // Builds the response.
    KeyPredicate startKP = (uri_info.getKeyPredicates().isEmpty()) ? null : uri_info.getKeyPredicates().get(0);

    Map results = Navigator.<Map>navigate(uri_info.getStartEntitySet(), startKP,
            uri_info.getNavigationSegments(), Map.class);

    int inlineCount = -1;
    FilterExpression filter = uri_info.getFilter();
    OrderByExpression orderBy = uri_info.getOrderBy();

    if (uri_info.getInlineCount() != null && uri_info.getInlineCount().equals(InlineCount.ALLPAGES)
            && results instanceof SubMap && filter != null) {
        SubMapBuilder smb = ((SubMap) results).getSubMapBuilder();
        smb.setFilter(filter);
        results = smb.build();
        inlineCount = results.size();
    }

    // Skip, Sort and Filter.
    if (results instanceof SubMap && (filter != null || orderBy != null || skip != 0 || top != 0)) {
        SubMapBuilder smb = ((SubMap) results).getSubMapBuilder();
        smb.setFilter(filter).setOrderBy(orderBy);
        smb.setSkip(skip);
        smb.setTop(top);
        results = smb.build();
    }

    // Custom formats (eg: metalink, csv)
    if (uri_info.getFormat() != null) {
        if (uri_info.getFormat().equals(MetalinkBuilder.CONTENT_TYPE)) {
            return MetalinkFormatter.writeFeed(targetES, results.values(), makeLink().toString());
        }
        if (uri_info.getFormat().equals(CsvFormatter.CONTENT_TYPE)) {
            return CsvFormatter.writeFeed(targetES, results.values(), uri_info.getSelect());
        }
    }

    // Feeds the EntitySetResponseBuilder.
    final String requestLink = makeLink().toString();
    final Iterator<AbstractEntity> iterator = results.values().iterator();
    final Iterator<Map<String, Object>> it = new Iterator<Map<String, Object>>() {
        private AbstractEntity entity;

        @Override
        public boolean hasNext() {
            boolean value = iterator.hasNext();
            if (!value && entity != null) {
                try {
                    Closeable closeable = Closeable.class.cast(entity);
                    try {
                        closeable.close();
                    } catch (IOException e) {
                        LOGGER.warn("Cannot close resource: {}", entity);
                    }
                } catch (ClassCastException e) {
                }
            }
            return value;
        }

        @Override
        public Map<String, Object> next() {
            entity = iterator.next();
            return entity.toEntityResponse(requestLink);
        }

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

    ODataEntityProviderPropertiesBuilder builder = EntityProviderWriteProperties.serviceRoot(makeLink());

    // $expand.
    ExpandSelectTreeNode expand_select_tree = UriParser.createExpandSelectTree(uri_info.getSelect(),
            uri_info.getExpand());

    builder.expandSelectTree(expand_select_tree).callbacks(
            makeCallbacks(target.getExpandableNavLinkNames(), new Expander(makeLink(false), target, results)));

    // inlinecount.
    if (uri_info.getInlineCount() != null && uri_info.getInlineCount().equals(InlineCount.ALLPAGES)) {
        if (inlineCount == -1) {
            inlineCount = results.size();
        }
        builder.inlineCountType(uri_info.getInlineCount());
        builder.inlineCount(inlineCount);
    }

    return EntityProvider.writeFeed(content_type, targetES, new ListFromIterator<>(it), builder.build());
}