Example usage for com.google.common.collect Iterables isEmpty

List of usage examples for com.google.common.collect Iterables isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Iterables isEmpty.

Prototype

public static boolean isEmpty(Iterable<?> iterable) 

Source Link

Document

Determines if the given iterable contains no elements.

Usage

From source file:com.groupon.jenkins.dynamic.buildconfiguration.ConfigSection.java

public boolean isValid() {
    return Iterables.isEmpty(getValidationErrors());
}

From source file:eu.interedition.text.repository.TransactionLog.java

public synchronized TransactionLog notify(ExecutorService executorService,
        Iterable<Repository.Listener> listeners) {
    if (!Iterables.isEmpty(listeners)) {
        final boolean added = !(addedAnnotations.isEmpty() && addedTexts.isEmpty());
        final boolean removed = !(removedAnnotations.isEmpty() && removedTexts.isEmpty());
        if (added || removed) {
            final Long[] addedTexts = this.addedTexts.toArray(new Long[this.addedTexts.size()]);
            final Long[] addedAnnotations = this.addedAnnotations
                    .toArray(new Long[this.addedAnnotations.size()]);
            final Long[] removedTexts = this.removedTexts.toArray(new Long[this.removedTexts.size()]);
            final Long[] removedAnnotations = this.removedAnnotations
                    .toArray(new Long[this.removedAnnotations.size()]);
            this.addedTexts.clear();
            this.removedTexts.clear();
            this.addedAnnotations.clear();
            this.removedAnnotations.clear();
            for (final Repository.Listener listener : listeners) {
                executorService.submit(new Callable<Void>() {
                    @Override/*from w w  w  .  jav a2  s.  c  o m*/
                    public Void call() throws Exception {
                        if (added) {
                            listener.added(addedTexts, addedAnnotations);
                        }
                        if (removed) {
                            listener.removed(removedTexts, removedAnnotations);
                        }
                        return null;
                    }
                });
            }
        }
    }
    return this;
}

From source file:org.eclipse.ziggurat.collect.collectors.WidthCollector.java

/**
 * Width wise collection./*from  w  w w .  j a va2 s .c  om*/
 * 
 * @param handler
 *        the handler that processes each element.
 * @param element
 *        : the current layer from which the collection is performed.
 * @throws CollectionAbortedException
 */
protected void collectWidthWise(ResultHandler<T> handler, Iterable<T> currentLayer)
        throws CollectionAbortedException {
    Iterable<T> nextLayer = Collections.emptyList();
    while (currentLayer != null && !Iterables.isEmpty(currentLayer)) {
        for (T currentElement : currentLayer) {
            try {
                handler.handleResult(currentElement);
                //Building the next layer.
                for (Picker<T> picker : this.getPickers()) {
                    Iterable<T> nexts = picker.getNexts(currentElement); //getting children.
                    if (nexts != null) {
                        nextLayer = Iterables.concat(nextLayer, nexts);
                    }
                }
            } catch (CannotHandleException e) {
                //do nothing
            } catch (Exception e) {
                throw new CollectionAbortedException(e);
            }
        }
        //The current layer has been processed. Going through the next one.
        currentLayer = nextLayer;
        nextLayer = Collections.emptyList();
    }
}

From source file:org.pentaho.community.di.util.GraphUtils.java

public static List<Vertex> getInputSteps(Graph g) {
    GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<>(g);
    return pipe.V().filter(new PipeFunction<Vertex, Boolean>() {
        @Override/*from w w w  . ja v a 2 s. c o m*/
        public Boolean compute(Vertex vertex) {
            return Iterables.isEmpty(vertex.getEdges(Direction.IN));
        }
    }).toList();
}

From source file:com.palantir.atlasdb.transaction.impl.CachingTransaction.java

@Override
public SortedMap<byte[], RowResult<byte[]>> getRows(String tableName, Iterable<byte[]> rows,
        ColumnSelection columnSelection) {
    if (Iterables.isEmpty(rows)) {
        log.info("Attempted getRows on '{}' table and {} with empty rows argument", tableName, columnSelection);
        return AbstractTransaction.EMPTY_SORTED_ROWS;
    }/*from   w w w  .  j  a v  a2 s  .  com*/

    ConcurrentMap<Cell, byte[]> colCache = getColCacheForTable(tableName);
    if (columnSelection.allColumnsSelected()) {
        SortedMap<byte[], RowResult<byte[]>> loaded = super.getRows(tableName, rows, columnSelection);
        cacheLoadedRows(colCache, loaded.values());
        return loaded;
    } else {
        Set<byte[]> toLoad = Sets.newHashSet();
        ImmutableSortedMap.Builder<byte[], RowResult<byte[]>> inCache = ImmutableSortedMap
                .orderedBy(UnsignedBytes.lexicographicalComparator());
        for (byte[] row : rows) {
            ImmutableSortedMap.Builder<byte[], byte[]> matches = ImmutableSortedMap
                    .orderedBy(UnsignedBytes.lexicographicalComparator());
            boolean nonEmpty = false;
            boolean shouldLoad = false;
            for (byte[] col : columnSelection.getSelectedColumns()) {
                byte[] val = colCache.get(Cell.create(row, col));
                if (val == null) {
                    shouldLoad = true;
                    break;
                } else if (val.length != 0) {
                    matches.put(col, val);
                    nonEmpty = true;
                }
            }
            if (shouldLoad) {
                toLoad.add(row);
            } else if (nonEmpty) {
                inCache.put(row, RowResult.create(row, matches.build()));
            }
        }
        SortedMap<byte[], RowResult<byte[]>> results = super.getRows(tableName, toLoad, columnSelection);
        cacheLoadedRows(colCache, results.values());
        inCache.putAll(results);
        return inCache.build();
    }
}

From source file:brooklyn.location.docker.strategy.GroupPlacementStrategy.java

@Override
public boolean apply(DockerHostLocation input) {
    boolean requireExclusive = config().get(REQUIRE_EXCLUSIVE);
    String dockerApplicationId = input.getOwner().getApplicationId();
    Iterable<Entity> deployed = Iterables.filter(input.getDockerContainerList(),
            Predicates.not(EntityPredicates.applicationIdEqualTo(dockerApplicationId)));
    Entity parent = entity.getParent();
    String applicationId = entity.getApplicationId();
    Iterable<Entity> sameApplication = Iterables.filter(deployed,
            EntityPredicates.applicationIdEqualTo(applicationId));
    if (requireExclusive && Iterables.size(deployed) > Iterables.size(sameApplication)) {
        LOG.debug("Found entities not in {}; required exclusive. Reject: {}", applicationId, input);
        return false;
    }//from w  ww . j  a  va 2s .c  o  m
    if (Iterables.isEmpty(sameApplication)) {
        LOG.debug("No entities present from {}. Accept: {}", applicationId, input);
        return true;
    } else {
        Iterable<Entity> sameParent = Iterables.filter(sameApplication, EntityPredicates.isChildOf(parent));
        if (Iterables.isEmpty(sameParent)) {
            LOG.debug("All entities from {} have different parent. Reject: {}", applicationId, input);
            return false;
        } else {
            LOG.debug("All entities from {} have same parent. Accept: {}", applicationId, input);
            return true;
        }
    }
}

From source file:brooklyn.location.docker.strategy.affinity.DockerAffinityRuleStrategy.java

@Override
public List<DockerHostLocation> filterLocations(List<DockerHostLocation> locations, Entity entity) {
    List<DockerHostLocation> available = Lists.newArrayList();

    // Select hosts that satisfy the affinity rules
    for (DockerHostLocation machine : locations) {
        Optional<List<String>> entityRules = Optional
                .fromNullable(entity.config().get(DockerHost.DOCKER_HOST_AFFINITY_RULES));
        Optional<List<String>> hostRules = Optional
                .fromNullable(machine.getOwner().config().get(DockerHost.DOCKER_HOST_AFFINITY_RULES));
        Optional<List<String>> infrastructureRules = Optional.fromNullable(
                machine.getOwner().getInfrastructure().config().get(DockerHost.DOCKER_HOST_AFFINITY_RULES));
        Iterable<String> combined = Iterables.concat(
                Optional.presentInstances(ImmutableList.of(entityRules, hostRules, infrastructureRules)));
        AffinityRules rules = AffinityRules.rulesFor(entity).parse(combined);

        Iterable<Entity> entities = getBrooklynManagementContext().getEntityManager()
                .findEntities(EntityPredicates.locationsIncludes(machine));
        if (Iterables.isEmpty(entities)) {
            if (rules.allowEmptyLocations()) {
                available.add(machine);//from  w  ww.j a  v a2s.c o  m
            }
        } else {
            Iterable<Entity> filtered = Iterables.filter(entities, rules);
            if (Iterables.size(filtered) == Iterables.size(entities)) {
                available.add(machine);
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Available Docker hosts: {}", Iterables.toString(available));
    }
    return available;
}

From source file:org.apache.brooklyn.entity.stock.BasicStartableImpl.java

@Override
public void start(Collection<? extends Location> locations) {
    try {//from   w ww  . ja va  2 s .com
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

        addLocations(locations);
        locations = Locations.getLocationsCheckingAncestors(locations, this);
        log.info("Starting entity " + this + " at " + locations);

        // essentially does StartableMethods.start(this, locations),
        // but optionally filters locations for each child

        Locations.LocationsFilter filter = getConfig(LOCATIONS_FILTER);
        Iterable<Entity> startables = filterStartableManagedEntities(getChildren());
        if (!Iterables.isEmpty(startables)) {
            List<Task<?>> tasks = Lists.newArrayListWithCapacity(Iterables.size(startables));
            for (final Entity entity : startables) {
                Collection<? extends Location> l2 = locations;
                if (filter != null) {
                    l2 = filter.filterForContext(new ArrayList<Location>(locations), entity);
                    log.debug("Child " + entity + " of " + this + " being started in filtered location list: "
                            + l2);
                }
                tasks.add(Entities.invokeEffectorWithArgs(this, entity, Startable.START, l2));
            }
            for (Task<?> t : tasks) {
                t.getUnchecked();
            }
        }
        sensors().set(Attributes.SERVICE_UP, true);
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } catch (Throwable t) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}

From source file:co.cask.cdap.shell.CommandSet.java

@Override
public void process(String[] args, PrintStream output) throws Exception {
    if (args.length == 0) {
        // TODO: print help message
        throw new InvalidCommandException();
    }/* w ww.  j  a  v a2s. c o  m*/

    String commandName = args[0];
    Iterable<Command> matches = commandsMap.getValuesForKeysStartingWith(commandName);
    if (Iterables.isEmpty(matches)) {
        throw new InvalidCommandException();
    }

    Command command = matches.iterator().next();
    command.process(Arrays.copyOfRange(args, 1, args.length), output);
}

From source file:org.tensorics.core.iterable.lang.QuantityIterableSupport.java

public final QuantifiedValue<V> varOf(Iterable<QuantifiedValue<V>> values) {
    if (Iterables.isEmpty(values)) {
        throw new IllegalArgumentException("Variance of empty value set is not possible.");
    }//www  .j av  a  2 s. c o m
    final QuantifiedValue<V> average = averageOf(values);

    // @formatter:off
    Iterable<QuantifiedValue<V>> squaredDifferences = StreamSupport.stream(values.spliterator(), false)
            .map(v -> calculate(v).minus(average)).map(difference -> calculate(difference).toThePowerOf(two()))
            .collect(Collectors.toList());
    // @formatter:on

    return averageOf(squaredDifferences);
}