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.camel.processor.Splitter.java

@SuppressWarnings("unchecked")
private Iterable<ProcessorExchangePair> createProcessorExchangePairsIterable(final Exchange exchange,
        final Object value) {
    final Iterator iterator = ObjectHelper.createIterator(value);
    return new Iterable() {
        // create a copy which we use as master to copy during splitting
        // this avoids any side effect reflected upon the incoming exchange
        private final Exchange copy = ExchangeHelper.createCopy(exchange, true);
        private final RouteContext routeContext = exchange.getUnitOfWork() != null
                ? exchange.getUnitOfWork().getRouteContext()
                : null;/*w w w.  ja va 2s .c o  m*/

        public Iterator iterator() {
            return new Iterator() {
                private int index;
                private boolean closed;

                public boolean hasNext() {
                    if (closed) {
                        return false;
                    }

                    boolean answer = iterator.hasNext();
                    if (!answer) {
                        // we are now closed
                        closed = true;
                        // nothing more so we need to close the expression value in case it needs to be
                        if (value instanceof Closeable) {
                            IOHelper.close((Closeable) value, value.getClass().getName(), LOG);
                        } else if (value instanceof Scanner) {
                            // special for Scanner as it does not implement Closeable
                            ((Scanner) value).close();
                        }
                    }
                    return answer;
                }

                public Object next() {
                    Object part = iterator.next();
                    // create a correlated copy as the new exchange to be routed in the splitter from the copy
                    // and do not share the unit of work
                    Exchange newExchange = ExchangeHelper.createCorrelatedCopy(copy, false);
                    if (part instanceof Message) {
                        newExchange.setIn((Message) part);
                    } else {
                        Message in = newExchange.getIn();
                        in.setBody(part);
                    }
                    return createProcessorExchangePair(index++, getProcessors().iterator().next(), newExchange,
                            routeContext);
                }

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

    };
}

From source file:org.hippoecm.frontend.editor.builder.RenderPluginEditorPlugin.java

public RenderPluginEditorPlugin(final IPluginContext context, final IPluginConfig config) {
    super(context, config);

    renderContext = new RenderContext(context, config);
    builderContext = new BuilderContext(context, config);
    final boolean editable = (builderContext.getMode() == Mode.EDIT);

    final WebMarkupContainer container = new WebMarkupContainer("head");
    container.setOutputMarkupId(true);//from w w  w  . ja  v a2 s  .c  o  m
    add(container);

    add(CssClass.append(new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            return builderContext.hasFocus() ? "active" : StringUtils.EMPTY;
        }
    }));

    // add transitions from parent container
    container.add(new RefreshingView<ILayoutTransition>("transitions") {

        @Override
        protected Iterator<IModel<ILayoutTransition>> getItemModels() {
            final Iterator<ILayoutTransition> transitionIter = getTransitionIterator();
            return new Iterator<IModel<ILayoutTransition>>() {

                public boolean hasNext() {
                    return transitionIter.hasNext();
                }

                public IModel<ILayoutTransition> next() {
                    return new Model<>(transitionIter.next());
                }

                public void remove() {
                    transitionIter.remove();
                }

            };
        }

        @Override
        protected void populateItem(Item<ILayoutTransition> item) {
            final ILayoutTransition transition = item.getModelObject();
            AjaxLink<Void> link = new AjaxLink<Void>("link") {

                @Override
                public void onClick(AjaxRequestTarget target) {
                    layoutContext.apply(transition);
                }

                @Override
                protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
                    super.updateAjaxAttributes(attributes);
                    attributes.getAjaxCallListeners().add(new EventStoppingDecorator());
                }

            };
            link.setVisible(editable);

            final String name = transition.getName();
            final Icon icon = getTransitionIconByName(name);

            link.add(CssClass.append(name));
            link.add(TitleAttribute.append(name));
            link.add(HippoIcon.fromSprite("icon", icon));
            item.add(link);
        }

    });

    final AjaxLink removeLink = new AjaxLink("remove") {

        @Override
        public void onClick(AjaxRequestTarget target) {
            if (validateDelete()) {
                builderContext.delete();
            }
        }

        @Override
        protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
            super.updateAjaxAttributes(attributes);
            attributes.getAjaxCallListeners().add(new EventStoppingDecorator());
        }

    };
    removeLink.setVisible(editable);
    removeLink.add(HippoIcon.fromSprite("icon", Icon.TIMES_CIRCLE));
    container.add(removeLink);

    if (editable) {
        add(new AjaxEventBehavior("onclick") {

            @Override
            protected void onEvent(AjaxRequestTarget target) {
                builderContext.focus();
            }

            @Override
            protected void updateAjaxAttributes(final AjaxRequestAttributes attributes) {
                super.updateAjaxAttributes(attributes);
                attributes.getAjaxCallListeners().add(new EventStoppingDecorator());
            }
        });

        builderContext.addBuilderListener(new IBuilderListener() {

            public void onBlur() {
                AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
                if (target != null) {
                    target.add(RenderPluginEditorPlugin.this);
                }
            }

            public void onFocus() {
                AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
                if (target != null) {
                    target.add(RenderPluginEditorPlugin.this);
                }
            }
        });
    }
}

From source file:org.apache.hadoop.yarn.server.api.records.impl.pb.NodeStatusPBImpl.java

private synchronized void addContainersToProto() {
    maybeInitBuilder();//from   ww w  . java  2s.  c o  m
    builder.clearContainersStatuses();
    if (containers == null)
        return;
    Iterable<ContainerStatusProto> iterable = new Iterable<ContainerStatusProto>() {
        @Override
        public Iterator<ContainerStatusProto> iterator() {
            return new Iterator<ContainerStatusProto>() {

                Iterator<ContainerStatus> iter = containers.iterator();

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

                @Override
                public ContainerStatusProto next() {
                    return convertToProtoFormat(iter.next());
                }

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

                }
            };

        }
    };
    builder.addAllContainersStatuses(iterable);
}

From source file:com.clxcommunications.xms.PagedFetcher.java

/**
 * Returns an iterable object that fetches and traverses all matching pages.
 * Each iteration will result in a network fetch.
 * <p>// w  w w.  j  a  va  2s  .c  om
 * This iterator will always yield at least one page, which might be empty.
 * <p>
 * Since the returned iterator will perform asynchronous network traffic it
 * is possible that the {@link Iterator#next()} method throws
 * {@link RuntimeException} having as cause an {@link ExecutionException}.
 * 
 * @return a non-null iterable
 * @throws RuntimeApiException
 *             if the background page fetching failed
 */
@Nonnull
public Iterable<Page<T>> pages() {

    return new Iterable<Page<T>>() {

        @Override
        public Iterator<Page<T>> iterator() {

            return new Iterator<Page<T>>() {

                private Page<T> page = null;
                private int seenElements = 0;

                @Override
                public boolean hasNext() {
                    if (page == null) {
                        return true;
                    } else {
                        return seenElements < page.totalSize() && !page.isEmpty();
                    }
                }

                @Override
                public Page<T> next() {
                    int pageToFetch = (page == null) ? 0 : page.page() + 1;

                    try {
                        page = fetchAsync(pageToFetch, null).get();
                    } catch (InterruptedException e) {
                        // Interrupt the thread to let upstream code know.
                        Thread.currentThread().interrupt();
                    } catch (ExecutionException e) {
                        ApiException cause;

                        try {
                            cause = Utils.unwrapExecutionException(e);
                        } catch (ApiException einner) {
                            cause = einner;
                        }

                        throw new RuntimeApiException(cause);
                    }

                    seenElements += page.size();

                    return page;
                }

            };

        }

    };
}

From source file:com.eaio.util.text.HumanTime.java

/**
 * Parses a {@link CharSequence} argument and returns a {@link HumanTime} instance.
 * // w  ww.ja v a2  s.c o m
 * @param s the char sequence, may not be <code>null</code>
 * @return an instance, never <code>null</code>
 */
public static HumanTime eval(final CharSequence s) {
    HumanTime out = new HumanTime(0L);

    int num = 0;

    int start = 0;
    int end = 0;

    State oldState = State.IGNORED;

    for (char c : new Iterable<Character>() {

        /**
         * @see java.lang.Iterable#iterator()
         */
        public Iterator<Character> iterator() {
            return new Iterator<Character>() {

                private int p = 0;

                /**
                 * @see java.util.Iterator#hasNext()
                 */
                public boolean hasNext() {
                    return p < s.length();
                }

                /**
                 * @see java.util.Iterator#next()
                 */
                public Character next() {
                    return s.charAt(p++);
                }

                /**
                 * @see java.util.Iterator#remove()
                 */
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }

    }) {
        State newState = getState(c);
        if (oldState != newState) {
            if (oldState == State.NUMBER && (newState == State.IGNORED || newState == State.UNIT)) {
                num = Integer.parseInt(s.subSequence(start, end).toString());
            } else if (oldState == State.UNIT && (newState == State.IGNORED || newState == State.NUMBER)) {
                out.nTimes(s.subSequence(start, end).toString(), num);
                num = 0;
            }
            start = end;
        }
        ++end;
        oldState = newState;
    }
    if (oldState == State.UNIT) {
        out.nTimes(s.subSequence(start, end).toString(), num);
    }

    return out;
}

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

@Override
public Iterable<Object> getObjects(String key) {
    try {/* ww w. ja  v a2 s. c om*/
        final JSONArray array = obj.getJSONArray(key);

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

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

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

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

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

From source file:com.espertech.esper.view.std.AddPropertyValueOptionalView.java

public final Iterator<EventBean> iterator() {
    final Iterator<EventBean> parentIterator = parent.iterator();

    return new Iterator<EventBean>() {
        public boolean hasNext() {
            return parentIterator.hasNext();
        }/*from ww w  .  j a v  a 2  s  .  co m*/

        public EventBean next() {
            EventBean nextEvent = parentIterator.next();
            if (mustAddProperty) {
                return addProperty(nextEvent, propertyNames, propertyValues, eventType,
                        agentInstanceContext.getStatementContext().getEventAdapterService());
            } else {
                return nextEvent;
            }
        }

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

From source file:net.minecraftforge.registries.ForgeRegistry.java

@Override
public Iterator<V> iterator() {
    return new Iterator<V>() {
        int cur = -1;
        V next = null;//  ww  w  . j  a  v  a  2  s  .  c  o m
        {
            next();
        }

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

        @Override
        public V next() {
            V ret = next;
            do {
                cur = availabilityMap.nextSetBit(cur + 1);
                next = ids.get(cur);
            } while (next == null && cur != -1); // nextSetBit returns -1 when none is found
            return ret;
        }
        //TODO add remove support?
    };
}

From source file:com.github.steveash.guavate.Guavate.java

/**
 * Creates a stream that combines two other streams, continuing until either stream ends.
 * <p>//ww w .j  a  va 2s  .co  m
 * The combiner function is called once for each pair of objects found in the input streams.
 * @param <A> the type of the first stream
 * @param <B> the type of the second stream
 * @param <R> the type of the resulting stream
 * @param stream1 the first stream
 * @param stream2 the first stream
 * @param zipper the function used to combine the pair of objects
 * @return a stream of pairs, one from each stream
 */
private static <A, B, R> Stream<R> zip(Stream<A> stream1, Stream<B> stream2, BiFunction<A, B, R> zipper) {
    // this is private for now, to see if it is really needed on the API
    // it suffers from generics problems at the call site with common zipper functions
    // as such, it is less useful than it might seem
    Spliterator<A> split1 = stream1.spliterator();
    Spliterator<B> split2 = stream2.spliterator();
    // merged stream lacks some characteristics
    int characteristics = split1.characteristics() & split2.characteristics()
            & ~(Spliterator.DISTINCT | Spliterator.SORTED);
    long size = Math.min(split1.getExactSizeIfKnown(), split2.getExactSizeIfKnown());

    Iterator<A> it1 = Spliterators.iterator(split1);
    Iterator<B> it2 = Spliterators.iterator(split2);
    Iterator<R> it = new Iterator<R>() {
        @Override
        public boolean hasNext() {
            return it1.hasNext() && it2.hasNext();
        }

        @Override
        public R next() {
            return zipper.apply(it1.next(), it2.next());
        }
    };
    Spliterator<R> split = Spliterators.spliterator(it, size, characteristics);
    return StreamSupport.stream(split, false);
}

From source file:com.github.mjeanroy.spring.mappers.InMemoryObjectMapperTest.java

@Test
public void it_should_create_linked_list_with_iterable_sources() throws Exception {
    ObjectMapper<Foo, FooDto> objectMapper = inMemoryObjectMapper(mapper, Foo.class, FooDto.class);

    final Iterator<Foo> iterator = new Iterator<Foo>() {
        @Override//from   ww w  . j a va2 s. co  m
        public boolean hasNext() {
            return false;
        }

        @Override
        public Foo next() {
            return null;
        }

        @Override
        public void remove() {
            // Nothing to do.
        }
    };

    Iterable<Foo> iterable = new Iterable<Foo>() {
        @Override
        public Iterator<Foo> iterator() {
            return iterator;
        }
    };

    Iterable<FooDto> results = objectMapper.map(iterable);

    assertThat(results).isInstanceOf(LinkedList.class);
}