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:org.apache.aurora.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}.//  w  w  w  .j  a va  2  s .co  m
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Amount<Integer, Time> sessionTimeout, Optional<Credentials> credentials,
        Optional<String> chrootPath, Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = Preconditions.checkNotNull(sessionTimeout).as(Time.MILLISECONDS);
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            InetSocketAddressHelper::toString);
    this.zooKeeperServers = Joiner.on(',').join(servers).concat(chrootPath.or(""));
}

From source file:org.eclipse.sirius.diagram.sequence.internal.tool.command.builders.SequenceCreatedEventsFlaggingSiriusCommand.java

private Option<DDiagramElement> safeAddCreationFlag(DDiagramElement dde, Rectangle toolCreationFlag) {
    if (Iterables.isEmpty(Iterables.filter(dde.getGraphicalFilters(), AbsoluteBoundsFilter.class))) {
        AbsoluteBoundsFilter flag = getFlag(toolCreationFlag);

        if (LostMessageEnd.viewpointElementPredicate().apply(dde) && lostNodesLocation != null) {
            flag.setY(lostNodesLocation.y);
        }/*from   www . j  a  v a  2 s. c o  m*/

        dde.getGraphicalFilters().add(flag);
        return Options.newSome(dde);
    }
    return Options.newNone();
}

From source file:org.thiesen.ant.git.GitInfoExtractor.java

private static boolean isDirty(final CustomTag lastRevTag, final Repository r)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    final WorkingTreeIterator iterator = new FileTreeIterator(r);
    final IndexDiff d = lastRevTag == null ? new IndexDiff(r, Constants.HEAD, iterator)
            : new IndexDiff(r, lastRevTag.getObjectId(), iterator);
    d.diff();/* w ww  .j av  a 2  s.c om*/

    @SuppressWarnings("unchecked")
    final Iterable<String> allModifications = Iterables.filter(
            Iterables.concat(d.getAdded(), d.getModified(), d.getChanged(), d.getMissing(), d.getRemoved()),
            new NotIsGitlink(r));

    return !Iterables.isEmpty(allModifications);
}

From source file:org.esupportail.publisher.repository.externals.ldap.LdapUserDaoImpl.java

@Override
public List<IExternalUser> getUsersFromParentGroups(final Iterable<String> groupIds, final String search) {
    final String userAttrGroup = this.externalUserHelper.getUserGroupAttribute();
    if (userAttrGroup != null && !userAttrGroup.isEmpty() && groupIds != null && !Iterables.isEmpty(groupIds)) {
        OrFilter groupFilter = new OrFilter();
        boolean emptyFilter = true;
        for (String groupId : groupIds) {
            if (groupId != null && !groupId.trim().isEmpty()) {
                groupFilter//w w  w .j a v  a  2 s  . co m
                        .or(new LikeFilter(externalUserHelper.getUserGroupAttribute(), groupId.trim() + "*"));
                emptyFilter = false;
            }
        }
        if (emptyFilter)
            return new LinkedList<IExternalUser>();

        AndFilter filter = new AndFilter().and(groupFilter);
        if (search != null && !search.trim().isEmpty()) {
            filter.and(
                    new WhitespaceWildcardsFilter(externalUserHelper.getUserSearchAttribute(), search.trim()));
        }
        return searchWithFilter(filter);
    }
    return new LinkedList<IExternalUser>();
}

From source file:org.obm.push.protocol.data.SyncEncoder.java

private void appendCommands(Element collectionElement, Iterable<SyncCollectionCommandRequest> commands,
        Device device) {//from   ww  w  . j a  v a 2  s .com
    if (Iterables.isEmpty(commands)) {
        return;
    }
    Element commandsElement = DOMUtils.createElement(collectionElement, SyncRequestFields.COMMANDS.getName());
    for (SyncCollectionCommandRequest command : commands) {
        appendCommand(commandsElement, command, device);
    }
}

From source file:org.summer.dsl.xbase.typesystem.internal.ScopeProviderAccess.java

/**
 * Returns a bunch of descriptions most of which are actually {@link IIdentifiableElementDescription describing identifiables}. 
 * The provided iterable is never empty but it may contain a single {@link ErrorDescription error description}.
 * // w  w  w .  j av a 2 s  . c  om
 * @return the available descriptions.
 */
@NonNullByDefault
public Iterable<IEObjectDescription> getCandidateDescriptions(XExpression expression, EReference reference,
        @Nullable EObject toBeLinked, IFeatureScopeSession session, IResolvedTypes types)
        throws IllegalNodeException {
    if (toBeLinked == null) {
        return Collections.emptyList();
    }
    if (!toBeLinked.eIsProxy()) {
        throw new IllegalStateException(expression + " was already linked to " + toBeLinked);
    }
    URI uri = EcoreUtil.getURI(toBeLinked);
    String fragment = uri.fragment();
    if (encoder.isCrossLinkFragment(expression.eResource(), fragment)) {
        INode node = encoder.getNode(expression, fragment);
        final EClass requiredType = reference.getEReferenceType();
        if (requiredType == null)
            return Collections.emptyList();

        final String crossRefString = linkingHelper.getCrossRefNodeAsString(node, true);
        if (crossRefString != null && !crossRefString.equals("")) {
            final IScope scope = session.getScope(expression, reference, types);
            QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
            Iterable<IEObjectDescription> descriptions = scope.getElements(qualifiedLinkName);
            if (Iterables.isEmpty(descriptions)) {
                INode errorNode = getErrorNode(expression, node);
                if (errorNode != node) {
                    qualifiedLinkName = getErrorName(errorNode);
                }
                return Collections.<IEObjectDescription>singletonList(
                        new ErrorDescription(getErrorNode(expression, node), qualifiedLinkName));
            }
            return descriptions;
        }
        return Collections.emptyList();
    } else {
        throw new IllegalStateException(expression + " uses unsupported uri fragment " + uri);
    }
}

From source file:org.eclipse.xtext.xbase.typesystem.internal.ScopeProviderAccess.java

/**
 * Returns a bunch of descriptions most of which are actually {@link IIdentifiableElementDescription describing identifiables}. 
 * The provided iterable is never empty but it may contain a single {@link ErrorDescription error description}.
 * /*from  w  w w .ja va 2s.co  m*/
 * @return the available descriptions.
 */
public Iterable<IEObjectDescription> getCandidateDescriptions(XExpression expression, EReference reference,
        /* @Nullable */ EObject toBeLinked, IFeatureScopeSession session, IResolvedTypes types)
        throws IllegalNodeException {
    if (toBeLinked == null) {
        return Collections.emptyList();
    }
    if (!toBeLinked.eIsProxy()) {
        throw new IllegalStateException(expression + " was already linked to " + toBeLinked);
    }
    URI uri = EcoreUtil.getURI(toBeLinked);
    String fragment = uri.fragment();
    if (encoder.isCrossLinkFragment(expression.eResource(), fragment)) {
        INode node = encoder.getNode(expression, fragment);
        final EClass requiredType = reference.getEReferenceType();
        if (requiredType == null)
            return Collections.emptyList();

        final String crossRefString = linkingHelper.getCrossRefNodeAsString(node, true);
        if (crossRefString != null && !crossRefString.equals("")) {
            QualifiedName qualifiedLinkName = qualifiedNameConverter.toQualifiedName(crossRefString);
            if (!qualifiedLinkName.isEmpty()) {
                final IScope scope = session.getScope(expression, reference, types);
                Iterable<IEObjectDescription> descriptions = scope.getElements(qualifiedLinkName);
                if (Iterables.isEmpty(descriptions)) {
                    INode errorNode = getErrorNode(expression, node);
                    if (errorNode != node) {
                        qualifiedLinkName = getErrorName(errorNode);
                    }
                    return Collections.<IEObjectDescription>singletonList(
                            new ErrorDescription(getErrorNode(expression, node), qualifiedLinkName));
                }
                return descriptions;
            } else {
                return Collections
                        .<IEObjectDescription>singletonList(new ErrorDescription(null /* followUp problem */));
            }
        }
        return Collections.emptyList();
    } else {
        throw new IllegalStateException(expression + " uses unsupported uri fragment " + uri);
    }
}

From source file:eu.trentorise.opendata.semtext.SemTexts.java

/**
 *
 * Checks spans are all be valid spans (see {@link SemTexts#checkSpan(int, int, Object)
 * }/*from  ww w  . j a  v a  2s .  c  om*/
 * and are non-overlapping (a span end offset may coincide with next span
 * start offset). Spans must be contained within {@code leftOffset} and
 * {@code rightOffset} (last span end offset may coincide with
 * {@code rightOffset}).
 *
 * @param prependedErrorMessage the exception message to use if the check
 * fails; will be converted to a string using String.valueOf(Object) and
 * prepended to more specific error messages.
 *
 * @throws IllegalArgumentException on invalid spans
 */
public static void checkSpans(Iterable<? extends Span> spans, int leftOffset, int rightOffset,
        @Nullable Object prependedErrorMessage) {

    checkArgument(spans != null, "%s -- spans are null!", prependedErrorMessage);
    checkSpan(leftOffset, rightOffset, prependedErrorMessage);

    // check containment        
    if (!Iterables.isEmpty(spans)) {
        int lowerBound = Iterables.getFirst(spans, null).getStart();
        int upperBound = Iterables.getLast(spans).getEnd();
        if (lowerBound < leftOffset || upperBound > rightOffset) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Reason: Provided spans exceed container span! Expected: [" + leftOffset + ","
                    + rightOffset + "] - Found: [" + lowerBound + "," + upperBound + "]");
        }
    }

    // check overlaps
    @Nullable
    Span lastSpan = null;
    for (Span span : spans) {
        checkSpan(span.getStart(), span.getEnd(), prependedErrorMessage);
        if (lastSpan != null && lastSpan.getEnd() > span.getStart()) {
            throw new IllegalArgumentException(String.valueOf(prependedErrorMessage)
                    + " -- Found overlapping span! Span " + lastSpan + " overlaps with span " + span);
        }
        lastSpan = span;
    }

}

From source file:org.apache.giraph.comm.netty.NettyWorkerServer.java

/**
 * Resolve mutation requests./*w w  w . ja  v  a 2 s .  c o m*/
 *
 * @param graphState Graph state
 */
private void resolveMutations(GraphState<I, V, E, M> graphState) {
    Multimap<Integer, I> resolveVertexIndices = HashMultimap
            .create(service.getPartitionStore().getNumPartitions(), 100);
    // Add any mutated vertex indices to be resolved
    for (Entry<I, VertexMutations<I, V, E, M>> e : serverData.getVertexMutations().entrySet()) {
        I vertexId = e.getKey();
        Integer partitionId = service.getPartitionId(vertexId);
        if (!resolveVertexIndices.put(partitionId, vertexId)) {
            throw new IllegalStateException(
                    "resolveMutations: Already has missing vertex on this " + "worker for " + vertexId);
        }
    }
    // Keep track of the vertices which are not here but have received messages
    for (Integer partitionId : service.getPartitionStore().getPartitionIds()) {
        Iterable<I> destinations = serverData.getCurrentMessageStore()
                .getPartitionDestinationVertices(partitionId);
        if (!Iterables.isEmpty(destinations)) {
            Partition<I, V, E, M> partition = service.getPartitionStore().getPartition(partitionId);
            for (I vertexId : destinations) {
                if (partition.getVertex(vertexId) == null) {
                    if (!resolveVertexIndices.put(partitionId, vertexId)) {
                        throw new IllegalStateException("resolveMutations: Already has missing vertex on this "
                                + "worker for " + vertexId);
                    }
                }
            }
            service.getPartitionStore().putPartition(partition);
        }
    }
    // Resolve all graph mutations
    VertexResolver<I, V, E, M> vertexResolver = conf.createVertexResolver(graphState);
    for (Entry<Integer, Collection<I>> e : resolveVertexIndices.asMap().entrySet()) {
        Partition<I, V, E, M> partition = service.getPartitionStore().getPartition(e.getKey());
        for (I vertexIndex : e.getValue()) {
            Vertex<I, V, E, M> originalVertex = partition.getVertex(vertexIndex);

            VertexMutations<I, V, E, M> mutations = null;
            VertexMutations<I, V, E, M> vertexMutations = serverData.getVertexMutations().get(vertexIndex);
            if (vertexMutations != null) {
                synchronized (vertexMutations) {
                    mutations = vertexMutations.copy();
                }
                serverData.getVertexMutations().remove(vertexIndex);
            }
            Vertex<I, V, E, M> vertex = vertexResolver.resolve(vertexIndex, originalVertex, mutations,
                    serverData.getCurrentMessageStore().hasMessagesForVertex(vertexIndex));
            graphState.getContext().progress();

            if (LOG.isDebugEnabled()) {
                LOG.debug("resolveMutations: Resolved vertex index " + vertexIndex + " with original vertex "
                        + originalVertex + ", returned vertex " + vertex + " on superstep "
                        + service.getSuperstep() + " with mutations " + mutations);
            }
            if (vertex != null) {
                partition.putVertex(vertex);
            } else if (originalVertex != null) {
                partition.removeVertex(originalVertex.getId());
            }
        }
        service.getPartitionStore().putPartition(partition);
    }
    if (!serverData.getVertexMutations().isEmpty()) {
        throw new IllegalStateException("resolveMutations: Illegally " + "still has "
                + serverData.getVertexMutations().size() + " mutations left.");
    }
}

From source file:com.google.devtools.build.lib.actions.MiddlemanFactory.java

/**
 * Creates both normal and scheduling middlemen.
 *
 * <p>Note: there's no need to synchronize this method; the only use of a field is via a call to
 * another synchronized method (getArtifact()).
 *
 * @return null iff {@code inputs} is null or empty; the middleman file and the middleman action
 *         otherwise/*from   w  w w.j a v a  2  s.  co  m*/
 */
private Pair<Artifact, Action> createMiddleman(ActionOwner owner, String middlemanName, String purpose,
        Iterable<Artifact> inputs, Root middlemanDir, MiddlemanType middlemanType) {
    if (inputs == null || Iterables.isEmpty(inputs)) {
        return null;
    }

    Artifact stampFile = getStampFileArtifact(middlemanName, purpose, middlemanDir);
    Action action = new MiddlemanAction(owner, inputs, stampFile, purpose, middlemanType);
    actionRegistry.registerAction(action);
    return Pair.of(stampFile, action);
}