Example usage for java.lang Iterable iterator

List of usage examples for java.lang Iterable iterator

Introduction

In this page you can find the example usage for java.lang Iterable iterator.

Prototype

Iterator<T> iterator();

Source Link

Document

Returns an iterator over elements of type T .

Usage

From source file:co.cask.tigon.cli.DistributedFlowOperations.java

@Override
public State getStatus(String flowName) {
    try {//w  ww .  j a  v a 2  s. c o  m
        Iterable<TwillController> controllers = lookupFlow(flowName);
        sleepForZK(controllers);
        if (controllers.iterator().hasNext()) {
            State state = controllers.iterator().next().state();
            sleepForZK(state);
            return state;
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:com.jeanchampemont.notedown.note.NoteServiceTest.java

@Test
public void testGetNotes() {
    User user = new User();

    when(authenticationServiceMock.getCurrentUser()).thenReturn(user);
    when(repoMock.findByUserOrderByLastModificationDesc(user)).thenReturn(Collections.emptyList());

    Iterable<Note> result = sut.getNotes();

    verify(authenticationServiceMock).getCurrentUser();
    verify(repoMock).findByUserOrderByLastModificationDesc(user);

    assertFalse(result.iterator().hasNext());
}

From source file:io.orchestrate.client.integration.FetchTest.java

@Test
public void fetchEmptyEventsForObject() throws InterruptedException, ExecutionException, TimeoutException {
    final String key = generateString();
    final String value = "{}";
    final String eventType = generateString();

    KvStoreOperation kvStoreOp = new KvStoreOperation(TEST_COLLECTION, key, value);
    Future<KvMetadata> future_1 = client().execute(kvStoreOp);
    KvMetadata kvMetadata = future_1.get(3, TimeUnit.SECONDS);

    EventFetchOperation<String> eventFetchOp = new EventFetchOperation<String>(TEST_COLLECTION, key, eventType,
            String.class);
    Iterable<Event<String>> results = result(eventFetchOp);

    assertNotNull(kvMetadata);//w w  w  .  ja  v a2  s.  c  o  m
    assertNotNull(results);
    assertFalse(results.iterator().hasNext());
}

From source file:ml.shifu.shifu.core.correlation.CorrelationReducer.java

@Override
protected void reduce(IntWritable key, Iterable<CorrelationWritable> values, Context context)
        throws IOException, InterruptedException {
    // build final correlation column info
    CorrelationWritable finalCw = null;//w w w . j ava2  s . c o  m

    Iterator<CorrelationWritable> cwIt = values.iterator();
    while (cwIt.hasNext()) {
        CorrelationWritable cw = cwIt.next();

        if (!cw.isValid()) {
            // In this case, there is no need to process this one because all of inside value is null
            LOG.warn("Such CorrelationWritable has not been inited, so we ingore it");
            continue;
        }

        if (finalCw == null) {
            finalCw = initCw(cw.getAdjustCount().length);
        }
        finalCw.setColumnIndex(cw.getColumnIndex());
        finalCw.combine(cw);
    }

    if (finalCw == null) {
        LOG.warn("Key: {}, Reducer result is null because there is no useful correlationwritable from Mapper.",
                key.get());
        return;
    }

    this.outputKey.set(key.get());
    this.outputValue.set(new String(Base64.encodeBase64(objectToBytes(finalCw)), "utf-8"));
    context.write(outputKey, outputValue);
}

From source file:org.paxml.control.IterateTag.java

private ChildrenResultList visitIterable(Context context, Iterable<?> it) {
    return visitIterator(context, it.iterator());
}

From source file:com.amalto.core.storage.StagingStorage.java

@Override
public void update(Iterable<DataRecord> records) {
    final TransformIterator iterator = new TransformIterator(records.iterator(), new Transformer() {

        @Override/*from  w w  w .j  a v a2s.  com*/
        public Object transform(Object input) {
            DataRecord dataRecord = (DataRecord) input;
            DataRecordMetadata metadata = dataRecord.getRecordMetadata();
            Map<String, String> recordProperties = metadata.getRecordProperties();
            // Update on a record in staging reset all its match&merge information.
            String status = recordProperties.get(METADATA_STAGING_STATUS);
            StagingUpdateAction updateAction = updateActions.get(status);
            if (updateAction == null) {
                // Try to re-read status from database
                if (status == null) {
                    UserQueryBuilder readStatus = from(dataRecord.getType());
                    for (FieldMetadata keyField : dataRecord.getType().getKeyFields()) {
                        readStatus.where(eq(keyField,
                                StorageMetadataUtils.toString(dataRecord.get(keyField), keyField)));
                    }
                    StorageResults refreshedRecord = delegate.fetch(readStatus.getSelect());
                    for (DataRecord record : refreshedRecord) {
                        Map<String, String> refreshedProperties = record.getRecordMetadata()
                                .getRecordProperties();
                        updateAction = updateActions.get(refreshedProperties.get(METADATA_STAGING_STATUS));
                    }
                }
                // Database doesn't have any satisfying update action
                if (updateAction == null) {
                    updateAction = defaultUpdateAction; // Covers cases where update action isn't specified.
                }
            }
            recordProperties.put(Storage.METADATA_STAGING_STATUS, updateAction.value());
            recordProperties.put(Storage.METADATA_STAGING_ERROR, StringUtils.EMPTY);
            if (updateAction.resetTaskId()) {
                metadata.setTaskId(null);
            }
            return dataRecord;
        }
    });
    Iterable<DataRecord> transformedRecords = new Iterable<DataRecord>() {

        @Override
        public Iterator<DataRecord> iterator() {
            return iterator;
        }
    };
    delegate.update(transformedRecords);
}

From source file:de.taimos.dao.mongo.AbstractMongoDAO.java

/**
 * queries with the given string, sorts the result and returns the first element. <code>null</code> is returned if no element is found.
 * /* ww  w .j a  va  2  s .c o m*/
 * @param query the query string
 * @param sort the sort string
 * @param params the parameters to replace # symbols
 * @return the first element found or <code>null</code> if none is found
 */
protected final T findFirstByQuery(String query, String sort, Object... params) {
    Find find = this.collection.find(query, params);
    if ((sort != null) && !sort.isEmpty()) {
        find.sort(sort);
    }
    Iterable<T> as = find.limit(1).as(this.getEntityClass());
    Iterator<T> iterator = as.iterator();
    if (iterator.hasNext()) {
        return iterator.next();
    }
    return null;
}

From source file:com.examples.with.different.packagename.ClassHierarchyIncludingInterfaces.java

public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) {
    final Iterable<Class<?>> classes = new Iterable<Class<?>>() {

        @Override/*from  ww w . j  a  v a2s. co  m*/
        public Iterator<Class<?>> iterator() {
            final MutableObject<Class<?>> next = new MutableObject<Class<?>>(type);
            return new Iterator<Class<?>>() {

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

                @Override
                public Class<?> next() {
                    final Class<?> result = next.getValue();
                    next.setValue(result.getSuperclass());
                    return result;
                }

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

            };
        }

    };
    if (interfacesBehavior != Interfaces.INCLUDE) {
        return classes;
    }
    return new Iterable<Class<?>>() {

        @Override
        public Iterator<Class<?>> iterator() {
            final Set<Class<?>> seenInterfaces = new HashSet<Class<?>>();
            final Iterator<Class<?>> wrapped = classes.iterator();

            return new Iterator<Class<?>>() {
                Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();

                @Override
                public boolean hasNext() {
                    return interfaces.hasNext() || wrapped.hasNext();
                }

                @Override
                public Class<?> next() {
                    if (interfaces.hasNext()) {
                        final Class<?> nextInterface = interfaces.next();
                        seenInterfaces.add(nextInterface);
                        return nextInterface;
                    }
                    final Class<?> nextSuperclass = wrapped.next();
                    final Set<Class<?>> currentInterfaces = new LinkedHashSet<Class<?>>();
                    walkInterfaces(currentInterfaces, nextSuperclass);
                    interfaces = currentInterfaces.iterator();
                    return nextSuperclass;
                }

                private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
                    for (final Class<?> iface : c.getInterfaces()) {
                        if (!seenInterfaces.contains(iface)) {
                            addTo.add(iface);
                        }
                        walkInterfaces(addTo, iface);
                    }
                }

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

            };
        }
    };
}

From source file:name.martingeisse.webide.features.java.compiler.classpath.AbstractLibraryFileManager.java

@Override
public final Iterable<JavaFileObject> list(final Location location, final String packageName,
        final Set<Kind> kinds, final boolean recurse) throws IOException {
    logger.trace("listing library [" + libraryNameForLogging + "] files for location [" + location
            + "], package [" + packageName + "], kinds [" + StringUtils.join(kinds, ", ") + "], recurse ["
            + recurse + "]");
    final Iterable<JavaFileObject> superIterable = super.list(location, packageName, kinds, recurse);
    if (location == StandardLocation.CLASS_PATH && kinds.contains(Kind.CLASS)) {
        final Iterable<JavaFileObject> libraryIterable = listLibraryClassFiles(packageName, recurse);
        logger.trace(//from  ww w .  jav  a  2 s.  com
                "contributed files from this library: " + StringUtils.join(libraryIterable.iterator(), ", "));
        return new Iterable<JavaFileObject>() {
            @Override
            public Iterator<JavaFileObject> iterator() {
                return GenericTypeUtil
                        .unsafeCast(new IteratorChain(superIterable.iterator(), libraryIterable.iterator()));
            }
        };
    } else {
        logger.trace("no contribution from this library because of location/kinds");
        return superIterable;
    }
}

From source file:com.texeltek.accumulocloudbaseshim.FormatterShim.java

@Override
@SuppressWarnings("unchecked")
public void initialize(final Iterable<Map.Entry<Key, Value>> scanner, boolean printTimestamps) {
    impl.initialize(new Iterable<Map.Entry<cloudbase.core.data.Key, cloudbase.core.data.Value>>() {
        @Override/*ww w .ja  v a2 s. c  o m*/
        public Iterator<Map.Entry<cloudbase.core.data.Key, cloudbase.core.data.Value>> iterator() {
            return IteratorUtils.transformedIterator(scanner.iterator(), new Transformer() {
                @Override
                public Map.Entry<cloudbase.core.data.Key, cloudbase.core.data.Value> transform(Object input) {
                    Map.Entry<Key, Value> entry = (Map.Entry<Key, Value>) input;
                    return new AbstractMap.SimpleEntry<cloudbase.core.data.Key, cloudbase.core.data.Value>(
                            entry.getKey().impl, entry.getValue().impl);
                }
            });
        }
    }, printTimestamps);
}