Example usage for java.lang Iterable Iterable

List of usage examples for java.lang Iterable Iterable

Introduction

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

Prototype

Iterable

Source Link

Usage

From source file:com.evolveum.polygon.connector.ldap.ConnectionManager.java

public Iterable<LdapNetworkConnection> getAllConnections() {

    final Iterator<ServerDefinition> serversIterator = servers.iterator();

    return new Iterable<LdapNetworkConnection>() {

        @Override//  www .jav  a2s .com
        public Iterator<LdapNetworkConnection> iterator() {
            return new Iterator<LdapNetworkConnection>() {

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

                @Override
                public LdapNetworkConnection next() {
                    return getConnection(serversIterator.next());
                }

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

            };
        }
    };

}

From source file:org.omnaest.utils.structure.iterator.IterableUtils.java

/**
 * Returns an {@link Iterable} where the {@link Iterable#iterator()} instance returns only those elements where the respective
 * bit within the filter {@link BitSet} is set to true
 * //www.  j a  v a  2s  .co m
 * @param iterable
 * @param filter
 * @return new {@link Iterable}
 */
public static <E> Iterable<E> filtered(final Iterable<E> iterable, final BitSet filter) {
    return new Iterable<E>() {
        @Override
        public Iterator<E> iterator() {
            if (iterable != null) {
                return IteratorUtils.filtered(iterable.iterator(), filter);
            }
            return IteratorUtils.empty();
        }
    };
}

From source file:org.olap4j.xmla.server.impl.Util.java

/**
 * Applies a collection of filters to an iterable.
 *
 * @param iterable Iterable//from   www.  ja va2 s .co m
 * @param conds Zero or more conditions
 * @param <T> element type
 * @return Iterable that returns only members of underlying iterable for
 *     for which all conditions evaluate to true
 */
public static <T> Iterable<T> filter(final Iterable<T> iterable, final Predicate1<T>... conds) {
    final Predicate1<T>[] conds2 = optimizeConditions(conds);
    if (conds2.length == 0) {
        return iterable;
    }
    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                final Iterator<T> iterator = iterable.iterator();
                T next;
                boolean hasNext = moveToNext();

                private boolean moveToNext() {
                    outer: while (iterator.hasNext()) {
                        next = iterator.next();
                        for (Predicate1<T> cond : conds2) {
                            if (!cond.test(next)) {
                                continue outer;
                            }
                        }
                        return true;
                    }
                    return false;
                }

                public boolean hasNext() {
                    return hasNext;
                }

                public T next() {
                    T t = next;
                    hasNext = moveToNext();
                    return t;
                }

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

From source file:org.apache.accumulo.core.util.shell.commands.SetIterCommand.java

private ClassLoader getClassLoader(final CommandLine cl, final Shell shellState) throws AccumuloException,
        TableNotFoundException, AccumuloSecurityException, IOException, FileSystemException {

    boolean tables = cl.hasOption(OptUtil.tableOpt().getOpt()) || !shellState.getTableName().isEmpty();
    boolean namespaces = cl.hasOption(OptUtil.namespaceOpt().getOpt());

    String classpath = null;// w  ww  .j a v  a 2s  .c  om
    Iterable<Entry<String, String>> tableProps;

    if (namespaces) {
        try {
            tableProps = shellState.getConnector().namespaceOperations()
                    .getProperties(OptUtil.getNamespaceOpt(cl, shellState));
        } catch (NamespaceNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    } else if (tables) {
        tableProps = shellState.getConnector().tableOperations()
                .getProperties(OptUtil.getTableOpt(cl, shellState));
    } else {
        throw new IllegalArgumentException("No table or namespace specified");
    }
    for (Entry<String, String> entry : tableProps) {
        if (entry.getKey().equals(Property.TABLE_CLASSPATH.getKey())) {
            classpath = entry.getValue();
        }
    }

    ClassLoader classloader;

    if (classpath != null && !classpath.equals("")) {
        shellState.getConnector().instanceOperations().getSystemConfiguration()
                .get(Property.VFS_CONTEXT_CLASSPATH_PROPERTY.getKey() + classpath);

        try {
            AccumuloVFSClassLoader.getContextManager().setContextConfig(
                    new ContextManager.DefaultContextsConfig(new Iterable<Map.Entry<String, String>>() {
                        @Override
                        public Iterator<Entry<String, String>> iterator() {
                            try {
                                return shellState.getConnector().instanceOperations().getSystemConfiguration()
                                        .entrySet().iterator();
                            } catch (AccumuloException e) {
                                throw new RuntimeException(e);
                            } catch (AccumuloSecurityException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }));
        } catch (IllegalStateException ise) {
        }

        classloader = AccumuloVFSClassLoader.getContextManager().getClassLoader(classpath);
    } else {
        classloader = AccumuloVFSClassLoader.getClassLoader();
    }
    return classloader;
}

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 a2  s. c o m
        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:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Boolean> getBooleans(String key) {
    try {//from   w ww  . ja  v  a 2 s  . c o  m
        final JSONArray array = obj.getJSONArray(key);

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

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

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

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

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

From source file:com.couchbase.devex.CSVConfig.java

@Override
public Observable<Document> startImport() {
    FileInputStream csvFile;/*from   ww w  .  j a  v a 2s .com*/
    try {
        csvFile = new FileInputStream(getCsvFilePath());
        CsvMapper mapper = new CsvMapper();
        mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);
        CsvSchema csvSchema = CsvSchema.emptySchema().withColumnSeparator(getColumnSeparator())
                .withQuoteChar(getQuoteChar());
        ObjectReader reader = mapper.reader(String[].class);
        MappingIterator<String[]> it = reader.with(csvSchema).readValues(csvFile);
        if (!getSkipFirstLineForNames()) {
            String[] firstline = it.next();
            updateColumnNames(firstline);
        }
        return Observable.from(new Iterable<String[]>() {
            @Override
            public Iterator<String[]> iterator() {
                return it;
            }
        }).flatMap(line -> createNode(line));
    } catch (FileNotFoundException e) {
        return Observable.error(e);
    } catch (IOException e) {
        return Observable.error(e);
    }
}

From source file:org.polymap.core.data.feature.lucene.LuceneCache.java

public Iterable<Feature> getFeatures(final Query query) throws IOException {
    Timer timer = new Timer();

    LuceneQueryParser queryParser = new LuceneQueryParser(schema, query.getFilter());

    if (indexReader == null) {
        rwLock.writeLock().lock();/*from   www .j ava2  s .  c  om*/
        try {
            if (indexReader == null) {
                indexReader = IndexReader.open(directory, true);
                searcher = new IndexSearcher(indexReader);
                log.info("Index reloaded.");
            }
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    //        rwLock.readLock().lock();

    // check schema
    if (schema == null) {
        throw new RuntimeException("schema is null, call getFeatureType() first.");
    }

    // execute Lucene query
    TopDocs topDocs = searcher.search(queryParser.getQuery(), query.getMaxFeatures());
    final ScoreDoc[] scoreDocs = topDocs.scoreDocs;
    final int count = scoreDocs.length;
    log.info("    results: " + count + " (" + timer.elapsedTime() + "ms)");

    // skip unwanted properties
    final FieldSelector fieldSelector = new QueryFieldSelector(query);

    return new Iterable<Feature>() {
        public Iterator<Feature> iterator() {

            return new Iterator<Feature>() {

                private SimpleFeatureBuilder builder = new SimpleFeatureBuilder((SimpleFeatureType) schema);
                private int index = 0;
                private boolean unlocked = false;
                private int cacheHits = 0;

                protected void finalize() throws Throwable {
                    if (unlocked == false) {
                        rwLock.readLock().unlock();
                    }
                }

                public boolean hasNext() {
                    boolean result = index < count;
                    if (result == false && unlocked == false) {
                        //                            rwLock.readLock().unlock();
                        unlocked = true;
                    }
                    if (result == false) {
                        log.info("CACHE: gets=" + count + ", hits=" + cacheHits + ", cache=" + cache.size());
                    }
                    return result;
                }

                public Feature next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException("Query result count: " + scoreDocs.length);
                    }
                    try {
                        int docnum = scoreDocs[index++].doc;

                        Feature result = null;

                        result = cache.get(cacheKey(docnum, query));
                        if (result != null) {
                            ++cacheHits;
                            return result;
                        }

                        Document doc = searcher.doc(docnum, fieldSelector);
                        //                            result = new LuceneFeature( doc, (SimpleFeatureType)schema );

                        String fid = null;
                        for (Fieldable field : doc.getFields()) {
                            if (schema == null) {
                                throw new RuntimeException("schema is null, call getFeatureType() first.");
                            }
                            // fid
                            if (field.name().equals("fid")) {
                                fid = field.stringValue();
                                continue;
                            }

                            PropertyDescriptor descriptor = schema.getDescriptor(field.name());
                            if (descriptor == null) {
                                throw new RuntimeException("No descriptor for: " + field.name());
                            }
                            Class valueType = descriptor.getType().getBinding();
                            // Geometry
                            if (Geometry.class.isAssignableFrom(valueType)) {
                                Geometry geom = jsonCoder.read(new StringReader(field.stringValue()));
                                builder.set(field.name(), geom);
                            }
                            // other
                            else {
                                Object value = ValueCoder.decode(field, valueType);
                                builder.set(field.name(), value);
                            }
                        }
                        result = builder.buildFeature(fid);

                        cache.put(cacheKey(docnum, query), result);
                        return result;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

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

            };
        }
    };
}

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(/*ww  w  .j  av  a  2s  .  c om*/
                "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:org.apache.hadoop.yarn.server.api.records.impl.pb.NodeStatusPBImpl.java

private synchronized void addContainersToStretchToProto() {
    maybeInitBuilder();/*from  w w w .  j  a v  a2 s  . c  o m*/
    builder.clearContainersToStretch();
    if (containersToStretch == null)
        return;
    Iterable<ContainerIdProto> iterable = new Iterable<ContainerIdProto>() {
        @Override
        public Iterator<ContainerIdProto> iterator() {
            return new Iterator<ContainerIdProto>() {

                Iterator<ContainerId> iter = containersToStretch.iterator();

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

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

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

                }
            };

        }
    };
    builder.addAllContainersToStretch(iterable);
}