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.google.cloud.dataflow.sdk.runners.inprocess.InProcessEvaluationContext.java

/**
 * Handle the provided {@link InProcessTransformResult}, produced after evaluating the provided
 * {@link CommittedBundle} (potentially null, if the result of a root {@link PTransform}).
 *
 * <p>The result is the output of running the transform contained in the
 * {@link InProcessTransformResult} on the contents of the provided bundle.
 *
 * @param completedBundle the bundle that was processed to produce the result. Potentially
 *                        {@code null} if the transform that produced the result is a root
 *                        transform/* w ww  .  java2  s.co m*/
 * @param completedTimers the timers that were delivered to produce the {@code completedBundle},
 *                        or an empty iterable if no timers were delivered
 * @param result the result of evaluating the input bundle
 * @return the committed bundles contained within the handled {@code result}
 */
public CommittedResult handleResult(@Nullable CommittedBundle<?> completedBundle,
        Iterable<TimerData> completedTimers, InProcessTransformResult result) {
    Iterable<? extends CommittedBundle<?>> committedBundles = commitBundles(result.getOutputBundles());
    // Update watermarks and timers
    EnumSet<OutputType> outputTypes = EnumSet.copyOf(result.getOutputTypes());
    if (Iterables.isEmpty(committedBundles)) {
        outputTypes.remove(OutputType.BUNDLE);
    } else {
        outputTypes.add(OutputType.BUNDLE);
    }
    CommittedResult committedResult = CommittedResult.create(result,
            completedBundle == null ? null
                    : completedBundle.withElements((Iterable) result.getUnprocessedElements()),
            committedBundles, outputTypes);
    watermarkManager.updateWatermarks(completedBundle,
            result.getTimerUpdate().withCompletedTimers(completedTimers), committedResult,
            result.getWatermarkHold());
    // Update counters
    if (result.getCounters() != null) {
        mergedCounters.merge(result.getCounters());
    }
    // Update state internals
    CopyOnAccessInMemoryStateInternals<?> theirState = result.getState();
    if (theirState != null) {
        CopyOnAccessInMemoryStateInternals<?> committedState = theirState.commit();
        StepAndKey stepAndKey = StepAndKey.of(result.getTransform(),
                completedBundle == null ? null : completedBundle.getKey());
        if (!committedState.isEmpty()) {
            applicationStateInternals.put(stepAndKey, committedState);
        } else {
            applicationStateInternals.remove(stepAndKey);
        }
    }
    return committedResult;
}

From source file:com.datastax.driver.core.IndexMetadata.java

/**
 * Builds a string representation of the custom index options.
 *
 * @return String representation of the custom index options, similar to what Cassandra stores in
 * the 'index_options' column of the 'schema_columns' table in the 'system' keyspace.
 *///from w  w  w  . ja va 2 s.  com
private String getOptionsAsCql() {
    Iterable<Map.Entry<String, String>> filtered = Iterables.filter(options.entrySet(),
            new Predicate<Map.Entry<String, String>>() {
                @Override
                public boolean apply(Map.Entry<String, String> input) {
                    return !input.getKey().equals(TARGET_OPTION_NAME)
                            && !input.getKey().equals(CUSTOM_INDEX_OPTION_NAME);
                }
            });
    if (Iterables.isEmpty(filtered))
        return "";
    StringBuilder builder = new StringBuilder();
    builder.append("WITH OPTIONS = {");
    Iterator<Map.Entry<String, String>> it = filtered.iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> option = it.next();
        builder.append(String.format("'%s' : '%s'", option.getKey(), option.getValue()));
        if (it.hasNext())
            builder.append(", ");
    }
    builder.append("}");
    return builder.toString();
}

From source file:com.facebook.buck.parser.AbstractParser.java

@Override
public TargetGraph buildTargetGraph(ParsingContext parsingContext, Iterable<BuildTarget> toExplore)
        throws IOException, InterruptedException, BuildFileParseException {
    if (Iterables.isEmpty(toExplore)) {
        return TargetGraph.EMPTY;
    }//from w  w w. jav a  2  s .co  m

    AtomicLong processedBytes = new AtomicLong();
    try (PerBuildState state = perBuildStateFactory.create(parsingContext, permState, targetPlatforms.get(),
            processedBytes)) {
        return buildTargetGraph(state, toExplore, processedBytes);
    }
}

From source file:org.chaston.oakfunds.model.ModelManagerImpl.java

@Inject
ModelManagerImpl(SystemPropertiesManager systemPropertiesManager, LedgerManager ledgerManager, Store store,
        AuthorizationContext authorizationContext, SystemAuthenticationManager authenticationManager)
        throws StorageException {
    this.systemPropertiesManager = systemPropertiesManager;
    this.ledgerManager = ledgerManager;
    this.store = store;

    List<? extends SearchTerm> searchTerms = ImmutableList
            .of(AttributeSearchTerm.of(Model.ATTRIBUTE_BASE_MODEL, SearchOperator.EQUALS, true));
    Model baseModel;/* w  ww. ja  v  a2 s  . com*/
    try (AuthenticationScope authenticationScope = authenticationManager.authenticateSystem()) {
        try (SinglePermissionAssertion singlePermissionAssertion = authorizationContext
                .assertPermission("model.create")) {
            Iterable<Model> baseModels = store.findRecords(Model.TYPE, searchTerms,
                    ImmutableList.<OrderingTerm>of());
            if (Iterables.isEmpty(baseModels)) {
                Map<String, Object> attributes = new HashMap<>();
                attributes.put(Model.ATTRIBUTE_TITLE, "[base]");
                attributes.put(Model.ATTRIBUTE_BASE_MODEL, true);
                Transaction transaction = store.startTransaction();
                boolean success = false;
                try {
                    baseModel = store.createRecord(Model.TYPE, attributes);
                    success = true;
                } finally {
                    if (success) {
                        transaction.commit();
                    } else {
                        transaction.rollback();
                    }
                }
            } else {
                baseModel = Iterables.getOnlyElement(baseModels);
            }
        }
    }
    baseModelId = baseModel.getId();
}

From source file:org.jclouds.aws.ec2.util.TagFilters.java

private void putAll(FilterName key, Iterable<?> values) {
    if (values == null || Iterables.isEmpty(values)) {
        // If we add an empty or null set of values, replace the value in the
        // map entirely
        map.put(key, ImmutableSet.of());
    } else {/*from  w  w  w. j a  va2 s.  c o  m*/
        // Add the values, to a new set if required
        if (!map.containsKey(key)) {
            map.put(key, Sets.newHashSet());
        }
        Iterable<?> entries = map.get(key);
        map.put(key, Iterables.concat(entries, values));
    }
}

From source file:edu.udo.scaffoldhunter.gui.dialogs.TooltipConfigurationDialog.java

private JPanel buildPropertyPanel() {
    FormLayout layout = new FormLayout("p, 3dlu, c:p:g(.5), 3dlu, c:p:g(.5)");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.setDefaultDialogBorder();//from ww  w  .ja  v a2s. c o  m

    List<PropertyDefinition> propDefs = Orderings.PROPERTY_DEFINITION_BY_TITLE
            .sortedCopy(dataset.getPropertyDefinitions().values());

    Collections.sort(propDefs, Orderings.PROPERTY_DEFINITION_BY_PROPERTY_TYPE);
    Iterable<PropertyDefinition> molPropDefs = Iterables.filter(propDefs,
            Predicates.not(SHPredicates.IS_SCAFFOLD_PROPDEF));
    Iterable<PropertyDefinition> scaffoldPropDefs = Iterables.filter(propDefs,
            SHPredicates.IS_SCAFFOLD_PROPDEF);
    if (!Iterables.isEmpty(molPropDefs)) {
        builder.appendSeparator(I18n.get("Tooltip.PropertyTitles.Molecule"));
        builder.nextLine();
        buildTitle(builder, true);
        for (PropertyDefinition propDef : molPropDefs) {
            addProperty(builder, propDef);
            builder.nextLine();
        }
    }

    if (!Iterables.isEmpty(scaffoldPropDefs)) {
        builder.appendSeparator(I18n.get("Tooltip.PropertyTitles.Scaffold"));
        buildTitle(builder, false);
        for (PropertyDefinition propDef : scaffoldPropDefs) {
            addProperty(builder, propDef);
            builder.nextLine();
        }
    }

    return builder.getPanel();
}

From source file:org.apache.brooklyn.entity.machine.SetHostnameCustomizer.java

protected void registerEtcHosts(SshMachineLocation machine, String ip, Iterable<String> hostnames) {
    log.info("Updating /etc/hosts of " + machine + ": adding " + ip + " = " + hostnames);

    checkArgument(Strings.isNonBlank(ip) && Networking.isValidIp4(ip), "invalid IPv4 address %s", ip);
    if (Strings.isBlank(ip) || Iterables.isEmpty(hostnames))
        return;//from  w  ww  .  ja  va  2s  . co m
    String line = ip + " " + Joiner.on(" ").join(hostnames);
    exec(machine, true, "echo " + line + " >> /etc/hosts");
}

From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*from   ww w.j  av a  2  s  . co  m*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplStructStrategy.java

@Override
protected void validateAllNecessaryMethodsHandled(ModelSchemaExtractionContext<?> extractionContext,
        Collection<Method> allMethods, final Set<Method> handledMethods) {
    Iterable<Method> notHandled = Iterables.filter(allMethods, new Predicate<Method>() {
        @Override/*  w  w  w  .j a v  a2  s  .  c  o  m*/
        public boolean apply(Method method) {
            return method.getDeclaringClass().isAnnotationPresent(Managed.class)
                    && !handledMethods.contains(method);
        }
    });

    // TODO - should call out valid getters without setters
    if (!Iterables.isEmpty(notHandled)) {
        throw invalidMethods(extractionContext, "only paired getter/setter methods are supported", notHandled);
    }
}

From source file:com.samskivert.depot.DepotRepository.java

/**
 * Loads up all persistent records that match the supplied set of primary keys.
 *
 * @throws DatabaseException if any problem is encountered communicating with the database.
 *//*from w  ww. j a  va  2 s  .  co  m*/
public <T extends PersistentRecord> List<T> loadAll(Iterable<Key<T>> keys) throws DatabaseException {
    return Iterables.isEmpty(keys) ? Collections.<T>emptyList()
            : _ctx.invoke(new FindAllQuery.WithKeys<T>(_ctx, keys));
}