Example usage for com.google.common.collect Iterators emptyIterator

List of usage examples for com.google.common.collect Iterators emptyIterator

Introduction

In this page you can find the example usage for com.google.common.collect Iterators emptyIterator.

Prototype

@Deprecated
public static <T> UnmodifiableIterator<T> emptyIterator() 

Source Link

Document

Returns the empty iterator.

Usage

From source file:org.apache.crunch.io.seq.SeqFileReaderFactory.java

@Override
public Iterator<T> read(FileSystem fs, final Path path) {
    mapFn.initialize();// ww  w . j  a v a  2s.c om
    try {
        final SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, fs.getConf());
        return new AutoClosingIterator<T>(reader, new UnmodifiableIterator<T>() {
            boolean nextChecked = false;
            boolean hasNext = false;

            @Override
            public boolean hasNext() {
                if (nextChecked == true) {
                    return hasNext;
                }
                try {
                    hasNext = reader.next(key, value);
                    nextChecked = true;
                    return hasNext;
                } catch (IOException e) {
                    LOG.info("Error reading from path: {}", path, e);
                    return false;
                }
            }

            @Override
            public T next() {
                if (!nextChecked && !hasNext()) {
                    return null;
                }
                nextChecked = false;
                return mapFn.map(converter.convertInput(key, value));
            }
        });
    } catch (IOException e) {
        LOG.info("Could not read seqfile at path: {}", path, e);
        return Iterators.emptyIterator();
    }
}

From source file:org.locationtech.geogig.cli.plumbing.DiffTree.java

/**
 * Executes the diff-tree command with the specified options.
 *///from   w ww .java 2  s.co m
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (refSpec.size() > 2) {
        throw new CommandFailedException("Tree refspecs list is too long :" + refSpec);
    }

    if (treeStats && describe) {
        throw new CommandFailedException("Cannot use --describe and --tree-stats simultaneously");
    }

    GeoGIG geogig = cli.getGeogig();

    org.locationtech.geogig.api.plumbing.DiffTree diff = geogig
            .command(org.locationtech.geogig.api.plumbing.DiffTree.class);

    String oldVersion = resolveOldVersion();
    String newVersion = resolveNewVersion();

    diff.setOldVersion(oldVersion).setNewVersion(newVersion);

    Iterator<DiffEntry> diffEntries;
    if (paths.isEmpty()) {
        diffEntries = diff.setProgressListener(cli.getProgressListener()).call();
    } else {
        diffEntries = Iterators.emptyIterator();
        for (String path : paths) {
            Iterator<DiffEntry> moreEntries = diff.setPathFilter(path)
                    .setProgressListener(cli.getProgressListener()).call();
            diffEntries = Iterators.concat(diffEntries, moreEntries);
        }
    }

    DiffEntry diffEntry;
    HashMap<String, Long[]> stats = Maps.newHashMap();
    while (diffEntries.hasNext()) {
        diffEntry = diffEntries.next();
        StringBuilder sb = new StringBuilder();
        String path = diffEntry.newPath() != null ? diffEntry.newPath() : diffEntry.oldPath();

        if (describe) {
            sb.append(diffEntry.changeType().toString().charAt(0)).append(' ').append(path).append(LINE_BREAK);

            if (diffEntry.changeType() == ChangeType.MODIFIED) {
                FeatureDiff featureDiff = geogig.command(DiffFeature.class)
                        .setNewVersion(Suppliers.ofInstance(diffEntry.getNewObject()))
                        .setOldVersion(Suppliers.ofInstance(diffEntry.getOldObject())).call();
                Map<PropertyDescriptor, AttributeDiff> diffs = featureDiff.getDiffs();
                HashSet<PropertyDescriptor> diffDescriptors = Sets.newHashSet(diffs.keySet());
                NodeRef noderef = diffEntry.changeType() != ChangeType.REMOVED ? diffEntry.getNewObject()
                        : diffEntry.getOldObject();
                RevFeatureType featureType = geogig.command(RevObjectParse.class)
                        .setObjectId(noderef.getMetadataId()).call(RevFeatureType.class).get();
                Optional<RevObject> obj = geogig.command(RevObjectParse.class).setObjectId(noderef.objectId())
                        .call();
                RevFeature feature = (RevFeature) obj.get();
                ImmutableList<Optional<Object>> values = feature.getValues();
                ImmutableList<PropertyDescriptor> descriptors = featureType.sortedDescriptors();
                int idx = 0;
                for (PropertyDescriptor descriptor : descriptors) {
                    if (diffs.containsKey(descriptor)) {
                        AttributeDiff ad = diffs.get(descriptor);
                        sb.append(ad.getType().toString().charAt(0) + " " + descriptor.getName().toString()
                                + LINE_BREAK);
                        if (!ad.getType().equals(TYPE.ADDED)) {
                            Object value = ad.getOldValue().orNull();
                            sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                            sb.append(LINE_BREAK);
                        }
                        if (!ad.getType().equals(TYPE.REMOVED)) {
                            Object value = ad.getNewValue().orNull();
                            sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                            sb.append(LINE_BREAK);
                        }
                        diffDescriptors.remove(descriptor);
                    } else {
                        sb.append("U ").append(descriptor.getName().toString()).append(LINE_BREAK);
                        sb.append(TextValueSerializer.asString(values.get(idx))).append(LINE_BREAK);
                    }
                    idx++;
                }
                for (PropertyDescriptor descriptor : diffDescriptors) {
                    AttributeDiff ad = diffs.get(descriptor);
                    sb.append(ad.getType().toString().charAt(0) + " " + descriptor.getName().toString()
                            + LINE_BREAK);
                    if (!ad.getType().equals(TYPE.ADDED)) {
                        Object value = ad.getOldValue().orNull();
                        sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                        sb.append(LINE_BREAK);
                    }
                    if (!ad.getType().equals(TYPE.REMOVED)) {
                        Object value = ad.getNewValue().orNull();
                        sb.append(TextValueSerializer.asString(Optional.fromNullable(value)));
                        sb.append(LINE_BREAK);
                    }
                }
            } else {
                NodeRef noderef = diffEntry.changeType() == ChangeType.ADDED ? diffEntry.getNewObject()
                        : diffEntry.getOldObject();
                RevFeatureType featureType = geogig.command(RevObjectParse.class)
                        .setObjectId(noderef.getMetadataId()).call(RevFeatureType.class).get();
                Optional<RevObject> obj = geogig.command(RevObjectParse.class).setObjectId(noderef.objectId())
                        .call();
                RevFeature feature = (RevFeature) obj.get();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    sb.append(diffEntry.changeType().toString().charAt(0));
                    sb.append(' ');
                    sb.append(featureType.sortedDescriptors().get(i).getName().toString());
                    sb.append(LINE_BREAK);
                    sb.append(TextValueSerializer.asString(value));
                    sb.append(LINE_BREAK);
                    i++;
                }
                sb.append(LINE_BREAK);
            }
            sb.append(LINE_BREAK);
            cli.getConsole().println(sb.toString());
        } else if (treeStats) {
            String parent = NodeRef.parentPath(path);
            if (!stats.containsKey(parent)) {
                stats.put(parent, new Long[] { 0l, 0l, 0l });
            }
            Long[] counts = stats.get(parent);
            if (diffEntry.changeType() == ChangeType.ADDED) {
                counts[0]++;
            } else if (diffEntry.changeType() == ChangeType.REMOVED) {
                counts[1]++;
            } else if (diffEntry.changeType() == ChangeType.MODIFIED) {
                counts[2]++;
            }
        }

        else {
            sb.append(path).append(' ');
            sb.append(diffEntry.oldObjectId().toString());
            sb.append(' ');
            sb.append(diffEntry.newObjectId().toString());
            cli.getConsole().println(sb.toString());
        }

    }
    if (treeStats) {
        for (String path : stats.keySet()) {
            StringBuffer sb = new StringBuffer();
            sb.append(path);
            Long[] counts = stats.get(path);
            for (int i = 0; i < counts.length; i++) {
                sb.append(" " + counts[i].toString());
            }
            cli.getConsole().println(sb.toString());
        }
    }
}

From source file:org.geogit.api.plumbing.LsTreeOp.java

/**
 * @see java.util.concurrent.Callable#call()
 *///w  ww . j a v  a2 s.  co m
public Iterator<NodeRef> call() {

    if (ref == null) {
        ref = Ref.WORK_HEAD;
    }

    ObjectId parentObjectId = ObjectId.NULL;

    // is it just a ref name?
    Optional<Ref> reference = command(RefParse.class).setName(ref).call();
    if (reference.isPresent()) {
        if (reference.get().getObjectId().isNull()) {
            return Iterators.emptyIterator();
        }
    }
    Optional<RevObject> revObject = command(RevObjectParse.class).setRefSpec(ref).call(RevObject.class);

    Optional<NodeRef> treeRef = Optional.absent();

    if (!revObject.isPresent()) {
        if (Ref.WORK_HEAD.equals(ref)) { // we are requesting a listing of the whole working
                                         // tree but it is empty
            return Iterators.emptyIterator();
        }
        // let's try to see if it is a feature type or feature in the working tree
        NodeRef.checkValidPath(ref);

        treeRef = command(FindTreeChild.class).setParent(getWorkTree().getTree()).setChildPath(ref)
                .setIndex(true).call();

        Preconditions.checkArgument(treeRef.isPresent(), "Invalid reference: %s", ref);
        ObjectId treeId = treeRef.get().objectId();
        parentObjectId = treeRef.get().getMetadataId();
        revObject = command(RevObjectParse.class).setObjectId(treeId).call(RevObject.class);
    }

    checkArgument(revObject.isPresent(), "Invalid reference: %s", ref);

    final TYPE type = revObject.get().getType();
    switch (type) {
    case FEATURE:
        NodeRef nodeRef = treeRef.isPresent() ? treeRef.get() : null;
        List<NodeRef> nodeRefs = Lists.newArrayList();
        nodeRefs.add(nodeRef);
        // If show trees options is passed in show all trees that contain this feature
        if (this.strategy == Strategy.TREES_ONLY) {
            if (nodeRef != null) {
                while (!nodeRef.getParentPath().isEmpty()) {
                    treeRef = command(FindTreeChild.class).setParent(getWorkTree().getTree())
                            .setChildPath(nodeRef.getParentPath()).setIndex(true).call();
                    nodeRef = treeRef.get();
                    nodeRefs.add(nodeRef);
                }
            }
        }
        return nodeRefs.iterator();
    case COMMIT:
        RevCommit revCommit = (RevCommit) revObject.get();
        ObjectId treeId = revCommit.getTreeId();
        revObject = command(RevObjectParse.class).setObjectId(treeId).call(RevObject.class);
    case TREE:

        DepthTreeIterator.Strategy iterStrategy;

        switch (this.strategy) {
        case CHILDREN:
            iterStrategy = DepthTreeIterator.Strategy.CHILDREN;
            break;
        case FEATURES_ONLY:
            iterStrategy = DepthTreeIterator.Strategy.FEATURES_ONLY;
            break;
        case TREES_ONLY:
            iterStrategy = DepthTreeIterator.Strategy.TREES_ONLY;
            break;
        case DEPTHFIRST:
            iterStrategy = DepthTreeIterator.Strategy.RECURSIVE;
            break;
        case DEPTHFIRST_ONLY_FEATURES:
            iterStrategy = DepthTreeIterator.Strategy.RECURSIVE_FEATURES_ONLY;
            break;
        case DEPTHFIRST_ONLY_TREES:
            iterStrategy = DepthTreeIterator.Strategy.RECURSIVE_TREES_ONLY;
            break;
        default:
            throw new IllegalStateException("Unknown strategy: " + this.strategy);
        }

        final String path = ref.lastIndexOf(':') != -1 ? ref.substring(ref.lastIndexOf(':') + 1) : "";

        DepthTreeIterator iter = new DepthTreeIterator(path, parentObjectId, (RevTree) revObject.get(),
                getIndex().getDatabase(), iterStrategy);
        iter.setBoundsFilter(refBoundsFilter);
        return iter;
    default:
        throw new IllegalArgumentException(String.format("Invalid reference: %s", ref));
    }

}

From source file:org.janusgraph.graphdb.types.system.EmptyVertex.java

@Override
public Iterator<Vertex> vertices(Direction direction, String... edgeLabels) {
    return Iterators.emptyIterator();
}

From source file:org.tzi.use.uml.ocl.type.EnumType.java

@Override
public Iterable<? extends MClassifier> generalizationHierachie(boolean includeThis) {
    // We don't support generalization of enumerations, yet
    return new Iterable<MClassifier>() {
        @Override/*from   w ww .  ja  va2  s  .co  m*/
        public Iterator<MClassifier> iterator() {
            return Iterators.emptyIterator();
        }
    };
}

From source file:org.moe.designer.uipreview.RenderedView.java

@Override
public Iterator<RenderedView> iterator() {
    if (myChildren == null) {
        return Iterators.emptyIterator();
    }//from  www  .  j  a  v  a  2s  .  c  om

    return myChildren.iterator();
}

From source file:io.druid.client.CachingQueryRunner.java

@Override
public Sequence<T> run(Query<T> query, Map<String, Object> responseContext) {
    final CacheStrategy strategy = toolChest.getCacheStrategy(query);

    final boolean populateCache = query.getContextPopulateCache(true) && strategy != null
            && cacheConfig.isPopulateCache() && cacheConfig.isQueryCacheable(query);

    final boolean useCache = query.getContextUseCache(true) && strategy != null && cacheConfig.isUseCache()
            && cacheConfig.isQueryCacheable(query);

    final Cache.NamedKey key;
    if (strategy != null && (useCache || populateCache)) {
        key = CacheUtil.computeSegmentCacheKey(segmentIdentifier, segmentDescriptor,
                strategy.computeCacheKey(query));
    } else {/* w  w  w .  ja v  a 2s. c  om*/
        key = null;
    }

    if (useCache) {
        final Function cacheFn = strategy.pullFromCache();
        final byte[] cachedResult = cache.get(key);
        if (cachedResult != null) {
            final TypeReference cacheObjectClazz = strategy.getCacheObjectClazz();

            return Sequences.map(new BaseSequence<>(new BaseSequence.IteratorMaker<T, Iterator<T>>() {
                @Override
                public Iterator<T> make() {
                    try {
                        if (cachedResult.length == 0) {
                            return Iterators.emptyIterator();
                        }

                        return mapper.readValues(mapper.getFactory().createParser(cachedResult),
                                cacheObjectClazz);
                    } catch (IOException e) {
                        throw Throwables.propagate(e);
                    }
                }

                @Override
                public void cleanup(Iterator<T> iterFromMake) {
                }
            }), cacheFn);
        }
    }

    final Collection<ListenableFuture<?>> cacheFutures = Collections
            .synchronizedList(Lists.<ListenableFuture<?>>newLinkedList());
    if (populateCache) {
        final Function cacheFn = strategy.prepareForCache();
        final List<Object> cacheResults = Lists.newLinkedList();

        return Sequences.withEffect(Sequences.map(base.run(query, responseContext), new Function<T, T>() {
            @Override
            public T apply(final T input) {
                cacheFutures.add(backgroundExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        cacheResults.add(cacheFn.apply(input));
                    }
                }));
                return input;
            }
        }), new Runnable() {
            @Override
            public void run() {
                try {
                    Futures.allAsList(cacheFutures).get();
                    CacheUtil.populate(cache, mapper, key, cacheResults);
                } catch (Exception e) {
                    log.error(e, "Error while getting future for cache task");
                    throw Throwables.propagate(e);
                }
            }
        }, backgroundExecutorService);
    } else {
        return base.run(query, responseContext);
    }
}

From source file:org.geoserver.script.wfs.ScriptTransactionPlugin.java

Iterator<ScriptTxDelegate> delegates() {
    List<File> files;
    try {//from  w ww .j a v a2s  .  co  m
        files = Arrays.asList(scriptMgr.getWfsTxRoot().listFiles());
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Error listing files in wfs/tx directory", e);
        return Iterators.emptyIterator();
    }

    return Iterators.transform(files.iterator(), new Function<File, ScriptTxDelegate>() {
        @Override
        public ScriptTxDelegate apply(@Nullable File input) {
            return delegate(input);
        }
    });
}

From source file:org.jiemamy.utils.LogMarker.java

public Iterator<Marker> iterator() {
    if (refereceList != null) {
        return refereceList.iterator();
    } else {/*  ww w .  j  ava2 s  . com*/
        return Iterators.emptyIterator();
    }
}

From source file:org.tzi.use.uml.ocl.type.EnumType.java

@Override
public Iterable<? extends MClassifier> specializationHierachie(boolean includeThis) {
    // We don't support generalization of enumerations, yet
    return new Iterable<MClassifier>() {
        @Override//w w  w. j  a v  a  2  s . c  om
        public Iterator<MClassifier> iterator() {
            return Iterators.emptyIterator();
        }
    };
}