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.estatio.dom.agreement.Agreement.java

private AgreementRole findCurrentOrMostRecentAgreementRole(final AgreementRoleType agreementRoleType) {
    // all available roles
    final Iterable<AgreementRole> rolesOfType = Iterables.filter(getRoles(),
            AgreementRole.Predicates.whetherTypeIs(agreementRoleType));

    // try to find the one that is current...
    Iterable<AgreementRole> roles = Iterables.filter(rolesOfType,
            WithInterval.Predicates.<AgreementRole>whetherCurrentIs(true));

    // ... else the most recently ended one
    if (Iterables.isEmpty(roles)) {
        final List<AgreementRole> rolesInList = Lists.newArrayList(rolesOfType);
        roles = orderRolesByEffectiveEndDateReverseNullsFirst().leastOf(rolesInList, 1);
    }/*  www.jav a 2 s  .  com*/

    // and return the party
    final AgreementRole currentOrMostRecentRole = ValueUtils.firstElseNull(roles);
    return currentOrMostRecentRole;
}

From source file:io.prestosql.sql.ExpressionUtils.java

public static Function<Expression, Expression> expressionOrNullSymbols(
        final Predicate<Symbol>... nullSymbolScopes) {
    return expression -> {
        ImmutableList.Builder<Expression> resultDisjunct = ImmutableList.builder();
        resultDisjunct.add(expression);//from ww  w . j a v  a  2s  .  co  m

        for (Predicate<Symbol> nullSymbolScope : nullSymbolScopes) {
            List<Symbol> symbols = SymbolsExtractor.extractUnique(expression).stream().filter(nullSymbolScope)
                    .collect(toImmutableList());

            if (Iterables.isEmpty(symbols)) {
                continue;
            }

            ImmutableList.Builder<Expression> nullConjuncts = ImmutableList.builder();
            for (Symbol symbol : symbols) {
                nullConjuncts.add(new IsNullPredicate(symbol.toSymbolReference()));
            }

            resultDisjunct.add(and(nullConjuncts.build()));
        }

        return or(resultDisjunct.build());
    };
}

From source file:org.opendaylight.controller.sal.binding.codegen.impl.AbstractRuntimeCodeGenerator.java

@Override
public final <T extends RpcService> RpcRouter<T> getRouterFor(final Class<T> serviceType, final String name)
        throws RpcIsNotRoutedException {
    final RpcServiceMetadata metadata = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(),
            new Supplier<RpcServiceMetadata>() {
                @Override/*from   w w  w.  j  av a  2  s .c  o  m*/
                public RpcServiceMetadata get() {
                    try {
                        return getRpcMetadata(utils.asCtClass(serviceType));
                    } catch (ClassNotFoundException | NotFoundException e) {
                        throw new IllegalStateException(
                                String.format("Failed to load metadata for class %s", serviceType), e);
                    }
                }
            });

    if (Iterables.isEmpty(metadata.getContexts())) {
        throw new RpcIsNotRoutedException("Service doesn't have routing context associated.");
    }

    synchronized (utils) {
        final T instance = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(),
                routerSupplier(serviceType, metadata));
        return new RpcRouterCodegenInstance<T>(name, serviceType, instance, metadata.getContexts());
    }
}

From source file:org.apache.brooklyn.location.jclouds.DefaultConnectivityResolver.java

/**
 * Combines the given resolve options with the customiser's configuration to determine the
 * best address and credential pair for management. In particular, if the resolve options
 * allow it will check that the credential is actually valid for the address.
 *///from  w ww .j av a2  s. c  o  m
@Override
public ManagementAddressResolveResult resolve(JcloudsLocation location, NodeMetadata node, ConfigBag config,
        ConnectivityResolverOptions options) {
    LOG.debug("{} resolving management parameters for {}, node={}, config={}, options={}",
            new Object[] { this, location, node, config, options });
    final Stopwatch timer = Stopwatch.createStarted();
    // Should only be null in tests.
    final Entity contextEntity = getContextEntity(config);
    if (shouldPublishNetworks() && !options.isRebinding() && contextEntity != null) {
        publishNetworks(node, contextEntity);
    }
    HostAndPort hapChoice = null;
    LoginCredentials credChoice = null;

    final Iterable<HostAndPort> managementCandidates = getManagementCandidates(location, node, config, options);
    Iterable<LoginCredentials> credentialCandidates = Collections.emptyList();
    if (!Iterables.isEmpty(managementCandidates)) {
        credentialCandidates = getCredentialCandidates(location, node, options, config);

        // Try each pair of address and credential until one succeeds.
        if (shouldCheckCredentials() && options.pollForReachableAddresses()) {
            for (HostAndPort hap : managementCandidates) {
                for (LoginCredentials cred : credentialCandidates) {
                    LOG.trace("Testing host={} with credential={}", hap, cred);
                    if (checkCredential(location, hap, cred, config, options.isWindows())) {
                        hapChoice = hap;
                        credChoice = cred;
                        break;
                    }
                }
                if (hapChoice != null)
                    break;
            }
        } else if (shouldCheckCredentials()) {
            LOG.debug("{} set on {} but pollForFirstReachableAddress={}",
                    new Object[] { CHECK_CREDENTIALS.getName(), this, options.pollForReachableAddresses() });
        }
    }

    if (hapChoice == null) {
        LOG.trace("Choosing first management candidate given node={} and mode={}", node, getNetworkMode());
        hapChoice = Iterables.getFirst(managementCandidates, null);
    }
    if (hapChoice == null) {
        LOG.trace("Choosing first address of node={} in mode={}", node, getNetworkMode());
        final Iterator<String> hit = getResolvableAddressesWithMode(node).iterator();
        if (hit.hasNext())
            HostAndPort.fromHost(hit.next());
    }

    if (hapChoice == null) {
        LOG.error("None of the addresses of node {} are reachable in mode {}",
                new Object[] { node, getNetworkMode() });
        throw new IllegalStateException(
                "Could not determine management address for node: " + node + " in mode: " + getNetworkMode());
    }

    if (credChoice == null) {
        credChoice = Iterables.getFirst(credentialCandidates, null);
        if (credChoice == null) {
            throw new IllegalStateException("No credentials configured for " + location);
        }
    }

    if (contextEntity != null) {
        contextEntity.sensors().set(Attributes.ADDRESS, hapChoice.getHostText());
    }

    // Treat AWS as a special case because the DNS fully qualified hostname in AWS is
    // (normally?!) a good way to refer to the VM from both inside and outside of the region.
    if (!isNetworkModeSet() && !options.isWindows()) {
        final boolean lookupAwsHostname = Boolean.TRUE
                .equals(config.get(JcloudsLocationConfig.LOOKUP_AWS_HOSTNAME));
        String provider = config.get(JcloudsLocationConfig.CLOUD_PROVIDER);
        if (provider == null) {
            provider = location.getProvider();
        }
        if (options.waitForConnectable() && "aws-ec2".equals(provider) && lookupAwsHostname) {
            // getHostnameAws sshes to the machine and curls 169.254.169.254/latest/meta-data/public-hostname.
            try {
                LOG.debug("Resolving AWS hostname of {}", location);
                String result = location.getHostnameAws(hapChoice, credChoice, config);
                hapChoice = HostAndPort.fromParts(result, hapChoice.getPort());
                LOG.debug("Resolved AWS hostname of {}: {}", location, result);
            } catch (Exception e) {
                LOG.debug("Failed to resolve AWS hostname of " + location, e);
            }
        }
    }

    ManagementAddressResolveResult result = new ManagementAddressResolveResult(hapChoice, credChoice);
    LOG.debug("{} resolved management parameters for {} in {}: {}",
            new Object[] { this, location, Duration.of(timer), result });
    return result;
}

From source file:com.google.devtools.build.lib.rules.java.WriteBuildInfoPropertiesAction.java

@Override
public boolean isVolatile() {
    return includeVolatile && !Iterables.isEmpty(getInputs());
}

From source file:eu.trentorise.opendata.commons.validation.Preconditions.java

/**
 *
 * Checks if provided iterable is non null and non empty .
 *
 * @param errorMessageTemplate a template for the exception message should
 * the check fail. The message is formed by replacing each {@code %s}
 * placeholder in the template with an argument. These are matched by
 * position - the first {@code %s} gets {@code
 *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the
 * formatted message in square braces. Unmatched placeholders will be left
 * as-is.//  w  ww. j a v a2  s .  c o  m
 * @param errorMessageArgs the arguments to be substituted into the message
 * template. Arguments are converted to strings using
 * {@link String#valueOf(Object)}.
 * @throws IllegalArgumentException if {@code iterable} is empty or null
 * @throws NullPointerException if the check fails and either
 * {@code errorMessageTemplate} or {@code errorMessageArgs} is null (don't
 * let this happen)
 *
 * @return a non-null non-empty iterable
 */
public static <T> Iterable<T> checkNotEmpty(@Nullable Iterable<T> iterable,
        @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
    String formattedMessage = TodUtils.format(errorMessageTemplate, errorMessageArgs);

    checkArgument(iterable != null, "%s -- Reason: Found null iterable.", formattedMessage);
    if (Iterables.isEmpty(iterable)) {
        throw new IllegalArgumentException(formattedMessage + " -- Reason: Found empty iterable.");
    }
    return iterable;
}

From source file:org.apache.isis.viewer.wicket.model.models.EntityCollectionModel.java

/**
 * Factory.//from   w w w.  ja v a2 s . co  m
 */
public static EntityCollectionModel createStandalone(final ObjectAdapter collectionAsAdapter,
        final IsisSessionFactory sessionFactory) {
    final Iterable<Object> pojos = EntityCollectionModel.asIterable(collectionAsAdapter);

    final List<ObjectAdapterMemento> mementoList = Lists
            .newArrayList(Iterables.transform(pojos, ObjectAdapterMemento.Functions
                    .fromPojo(sessionFactory.getCurrentSession().getPersistenceSession())));

    final ObjectSpecification elementSpec;
    if (!Iterables.isEmpty(pojos)) {
        // dynamically determine the spec of the elements
        // (ie so a List<Object> can be rendered according to the runtime type of its elements, 
        // rather than the compile-time type
        final LowestCommonSuperclassClosure closure = new LowestCommonSuperclassClosure();
        Function<Object, Class<?>> function = new Function<Object, Class<?>>() {
            @Override
            public Class<?> apply(Object obj) {
                return obj.getClass();
            }
        };
        IterableExtensions.fold(Iterables.transform(pojos, function), closure);
        elementSpec = sessionFactory.getSpecificationLoader()
                .loadSpecification(closure.getLowestCommonSuperclass());
    } else {
        elementSpec = collectionAsAdapter.getElementSpecification();
    }

    final Class<?> elementType;
    int pageSize = PAGE_SIZE_DEFAULT_FOR_STANDALONE;
    if (elementSpec != null) {
        elementType = elementSpec.getCorrespondingClass();
        pageSize = pageSize(elementSpec.getFacet(PagedFacet.class), PAGE_SIZE_DEFAULT_FOR_STANDALONE);
    } else {
        elementType = Object.class;
    }

    return new EntityCollectionModel(elementType, mementoList, pageSize);
}

From source file:org.jclouds.aws.util.AWSUtils.java

public static <R extends HttpRequest> R indexMapOfIterableToFormValuesWithPrefix(R request, String prefix,
        String keySuffix, String valueSuffix, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Map<?, ?>,
            "this binder is only valid for Map<?,Iterable<?>>: " + input.getClass());
    Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input;
    Builder<String, String> builder = ImmutableMultimap.builder();
    int i = 1;//from w  w w. ja v a  2 s . c om
    for (Map.Entry<Object, Iterable<Object>> entry : map.entrySet()) {
        builder.put(prefix + "." + i + "." + keySuffix,
                checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
        Iterable<Object> iterable = entry.getValue();
        if (!Iterables.isEmpty(iterable)) {
            int j = 1;
            for (Object v : iterable) {
                builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
                j++;
            }
        }
        i++;
    }
    ImmutableMultimap<String, String> forms = builder.build();
    return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}

From source file:org.tensorics.core.tensor.Shapes.java

private static Shape combineBy(Iterable<Shape> shapes, BiFunction<Shape, Shape, Shape> combiner) {
    requireNonNull(shapes, "shapes must not be null");
    if (Iterables.isEmpty(shapes)) {
        throw new NoSuchElementException("At least one shape is required.");
    }/*w  w  w  . j  a  v a 2s  . c  o  m*/
    Shape resultingShape = null;
    for (Shape shape : shapes) {
        if (resultingShape == null) {
            resultingShape = shape;
        } else {
            resultingShape = combiner.apply(resultingShape, shape);
        }
    }
    return resultingShape;
}

From source file:org.apache.beam.runners.direct.portable.EvaluationContext.java

/**
 * Returns an {@link Optional} containing a bundle which contains all of the unprocessed elements
 * that were not processed from the {@code completedBundle}. If all of the elements of the {@code
 * completedBundle} were processed, or if {@code completedBundle} is null, returns an absent
 * {@link Optional}.// w w  w . ja  v  a  2s. c  o m
 */
private Optional<? extends CommittedBundle<?>> getUnprocessedInput(CommittedBundle<?> completedBundle,
        TransformResult<?> result) {
    if (completedBundle == null || Iterables.isEmpty(result.getUnprocessedElements())) {
        return Optional.absent();
    }
    CommittedBundle<?> residual = completedBundle.withElements((Iterable) result.getUnprocessedElements());
    return Optional.of(residual);
}