Example usage for com.google.common.base Optional presentInstances

List of usage examples for com.google.common.base Optional presentInstances

Introduction

In this page you can find the example usage for com.google.common.base Optional presentInstances.

Prototype

@Beta
public static <T> Iterable<T> presentInstances(final Iterable<? extends Optional<? extends T>> optionals) 

Source Link

Document

Returns the value of each present instance from the supplied optionals , in order, skipping over occurrences of Optional#absent .

Usage

From source file:com.twitter.common.args.apt.CmdLineProcessor.java

private Iterable<ArgInfo> processAnnotatedArgs(@Nullable final Set<String> parsedTypes,
        Set<? extends Element> args, final Class<? extends Annotation> argAnnotation) {

    return Optional.presentInstances(Iterables.transform(args, new Function<Element, Optional<ArgInfo>>() {
        @Override/*from  ww  w.  j  a v a 2  s .  c  o  m*/
        public Optional<ArgInfo> apply(Element arg) {
            @Nullable
            TypeElement containingType = processArg(parsedTypes, arg, argAnnotation);
            if (containingType == null) {
                return Optional.absent();
            } else {
                return Optional.of(new ArgInfo(getBinaryName(containingType), arg.getSimpleName().toString()));
            }
        }
    }));
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.alarms.AlarmManager.java

private static Map<String, Collection<String>> buildAccountIdToAlarmNamesMap(@Nullable final String accountId,
        @Nullable final Collection<String> alarmNames) {
    final Multimap<String, String> alarmNamesMultimap = HashMultimap.create();
    if (alarmNames != null) {
        if (accountId != null) {
            alarmNamesMultimap.putAll(accountId, alarmNames); // An ARN is also a valid name
        }// w  w w  . j av a  2 s  . c  o  m
        CollectionUtils.putAll(
                Optional.presentInstances(Iterables.transform(alarmNames,
                        CloudWatchResourceName.asArnOfType(CloudWatchResourceName.Type.alarm))),
                alarmNamesMultimap, CloudWatchResourceName.toNamespace(), CloudWatchResourceName.toName());
    }
    return alarmNamesMultimap.asMap();
}

From source file:com.facebook.swift.codec.metadata.ThriftStructMetadataBuilder.java

private void inferThriftFieldIds(Multimap<String, FieldMetadata> fieldsByName,
        Set<String> fieldsWithConflictingIds) {
    // for each name group, set the ids on the fields without ids
    for (Entry<String, Collection<FieldMetadata>> entry : fieldsByName.asMap().entrySet()) {
        Collection<FieldMetadata> fields = entry.getValue();

        // skip all entries without a name or singleton groups... we'll deal with these later
        if (fields.size() <= 1) {
            continue;
        }/*from www  .j ava2s .  c  o m*/

        // all ids used by this named field
        Set<Short> ids = ImmutableSet.copyOf(Optional.presentInstances(transform(fields, getThriftFieldId())));

        // multiple conflicting ids
        if (ids.size() > 1) {
            String fieldName = entry.getKey();
            if (!fieldsWithConflictingIds.contains(fieldName)) {
                metadataErrors.addError("ThriftStruct '%s' field '%s' has multiple ids: %s", structName,
                        fieldName, ids);
                fieldsWithConflictingIds.add(fieldName);
            }
            continue;
        }

        // single id, so set on all fields in this group (groups with no id are handled later)
        if (ids.size() == 1) {
            // propagate the id to all fields in this group
            short id = Iterables.getOnlyElement(ids);
            for (FieldMetadata field : fields) {
                field.setId(id);
            }
        }
    }
}

From source file:com.eucalyptus.auth.euare.RegionDelegatingPrincipalProvider.java

private <R, I> I regionDispatchAndReduce(
        final NonNullFunction<PrincipalProvider, Either<AuthException, R>> invoker, final I initial,
        final Function<I, Function<R, I>> reducer) throws AuthException {
    try {//from w w w.ja va  2 s.c om
        final Iterable<RegionInfo> regionInfos = regionConfigurationManager.getRegionInfos();
        final List<Either<AuthException, R>> regionResults = Lists.newArrayList();
        regionResults.add(invoker.apply(localProvider));
        if (!Iterables.isEmpty(regionInfos)) {
            final List<Future<Either<AuthException, R>>> regionResultFutures = Lists.newArrayList();
            withRegions: for (final RegionInfo regionInfo : regionInfos) {
                if (!RegionConfigurations.getRegionName().asSet().contains(regionInfo.getName())) {
                    for (final RegionInfo.RegionService service : regionInfo.getServices()) {
                        if ("identity".equals(service.getType())) {
                            final PrincipalProvider remoteProvider = new RemotePrincipalProvider(
                                    service.getEndpoints());
                            regionResultFutures.add(
                                    Threads.enqueue(Identity.class, RegionDelegatingPrincipalProvider.class,
                                            FUtils.cpartial(invoker, remoteProvider)));
                            continue withRegions;
                        }
                    }
                }
            }
            for (final Future<Either<AuthException, R>> future : regionResultFutures) {
                try {
                    regionResults.add(future.get());
                } catch (final InterruptedException e) {
                    throw new AuthException("Interrupted");
                } catch (final ExecutionException e) {
                    throw new RuntimeException(e); // Any AuthException caught and unwrapped below
                }
            }
        }
        final Iterable<R> successResults = Optional
                .presentInstances(Iterables.transform(regionResults, Either.<AuthException, R>rightOption()));
        if (Iterables.size(successResults) > 0) {
            return CollectionUtils.reduce(successResults, initial, reducer);
        }
        throw Iterables.get(Optional.presentInstances(
                Iterables.transform(regionResults, Either.<AuthException, R>leftOption())), 0);
    } catch (final RuntimeException e) {
        Exceptions.findAndRethrow(e, AuthException.class);
        throw e;
    }

}

From source file:com.facebook.swift.codec.metadata.AbstractThriftMetadataBuilder.java

protected final void inferThriftFieldIds(Multimap<String, FieldMetadata> fieldsByName,
        Set<String> fieldsWithConflictingIds) {
    // for each name group, set the ids on the fields without ids
    for (Entry<String, Collection<FieldMetadata>> entry : fieldsByName.asMap().entrySet()) {
        Collection<FieldMetadata> fields = entry.getValue();
        String fieldName = entry.getKey();

        // skip all entries without a name or singleton groups... we'll deal with these later
        if (fields.size() <= 1) {
            continue;
        }/*from  w w w  .ja  va  2  s.  co  m*/

        // all ids used by this named field
        Set<Short> ids = ImmutableSet.copyOf(Optional.presentInstances(transform(fields, getThriftFieldId())));

        // multiple conflicting ids
        if (ids.size() > 1) {
            if (!fieldsWithConflictingIds.contains(fieldName)) {
                metadataErrors.addError("Thrift class '%s' field '%s' has multiple ids: %s", structName,
                        fieldName, ids.toString());
                fieldsWithConflictingIds.add(fieldName);
            }
            continue;
        }

        // single id, so set on all fields in this group (groups with no id are handled later),
        // and validate isLegacyId is consistent and correct.
        if (ids.size() == 1) {
            short id = Iterables.getOnlyElement(ids);

            boolean isLegacyId = extractFieldIsLegacyId(id, fieldName, fields);

            // propagate the id data to all fields in this group
            for (FieldMetadata field : fields) {
                field.setId(id);
                field.setIsLegacyId(isLegacyId);
            }
        }
    }
}

From source file:com.facebook.swift.codec.metadata.AbstractThriftMetadataBuilder.java

protected final boolean extractFieldIsLegacyId(short id, String fieldName, Collection<FieldMetadata> fields) {
    Set<Boolean> isLegacyIds = ImmutableSet
            .copyOf(Optional.presentInstances(transform(fields, getThriftFieldIsLegacyId())));

    if (isLegacyIds.size() > 1) {
        metadataErrors.addError("Thrift class '%s' field '%s' has both isLegacyId=true and isLegacyId=false",
                structName, fieldName);/*from  w  ww .  ja v  a 2 s  . c o  m*/
    }
    if (id < 0) {
        if (!isLegacyIds.contains(true)) {
            metadataErrors.addError(
                    "Thrift class '%s' field '%s' has a negative field id but not isLegacyId=true", structName,
                    fieldName);
        }
    } else {
        if (isLegacyIds.contains(true)) {
            metadataErrors.addError(
                    "Thrift class '%s' field '%s' has isLegacyId=true but not a negative field id", structName,
                    fieldName);
        }
    }

    return id < 0;
}

From source file:com.facebook.buck.apple.WorkspaceAndProjectGenerator.java

private static void buildWorkspaceSchemeTests(Optional<BuildTarget> mainTarget, TargetGraph projectGraph,
        boolean includeProjectTests, boolean includeDependenciesTests,
        ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
        ImmutableSetMultimap<String, TargetNode<AppleTestDescription.Arg>> extraTestNodes,
        ImmutableSetMultimap.Builder<String, TargetNode<AppleTestDescription.Arg>> selectedTestsBuilder,
        ImmutableSetMultimap.Builder<String, TargetNode<?>> buildForTestNodesBuilder) {
    for (String schemeName : schemeNameToSrcTargetNode.keySet()) {
        ImmutableSet<TargetNode<?>> targetNodes = ImmutableSet
                .copyOf(Optional.presentInstances(schemeNameToSrcTargetNode.get(schemeName)));
        ImmutableSet<TargetNode<AppleTestDescription.Arg>> testNodes = getOrderedTestNodes(mainTarget,
                projectGraph, includeProjectTests, includeDependenciesTests, targetNodes,
                extraTestNodes.get(schemeName));
        selectedTestsBuilder.putAll(schemeName, testNodes);
        buildForTestNodesBuilder.putAll(schemeName, TopologicalSort.sort(projectGraph,
                Predicates.in(getTransitiveDepsAndInputs(projectGraph, testNodes, targetNodes))));
    }/*from  w w w .  j  ava 2 s.  co  m*/
}

From source file:com.facebook.buck.apple.WorkspaceAndProjectGenerator.java

private void writeWorkspaceSchemes(String workspaceName, Path outputDirectory,
        ImmutableMap<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigs,
        ImmutableSetMultimap<String, Optional<TargetNode<?>>> schemeNameToSrcTargetNode,
        ImmutableSetMultimap<String, TargetNode<?>> buildForTestNodes,
        ImmutableSetMultimap<String, TargetNode<AppleTestDescription.Arg>> ungroupedTests,
        ImmutableMap<PBXTarget, Path> targetToProjectPathMap,
        Iterable<PBXTarget> synthesizedCombinedTestTargets,
        Function<TargetNode<?>, Collection<PBXTarget>> targetNodeToPBXTargetTransformer,
        Function<BuildTarget, PBXTarget> buildTargetToPBXTargetTransformer) throws IOException {
    for (Map.Entry<String, XcodeWorkspaceConfigDescription.Arg> schemeConfigEntry : schemeConfigs.entrySet()) {
        String schemeName = schemeConfigEntry.getKey();
        boolean isMainScheme = schemeName.equals(workspaceName);
        XcodeWorkspaceConfigDescription.Arg schemeConfigArg = schemeConfigEntry.getValue();
        Iterable<PBXTarget> orderedBuildTargets = FluentIterable
                .from(ImmutableSet.copyOf(Optional.presentInstances(schemeNameToSrcTargetNode.get(schemeName))))
                .transformAndConcat(targetNodeToPBXTargetTransformer).toSet();
        FluentIterable<PBXTarget> orderedBuildTestTargets = FluentIterable
                .from(buildForTestNodes.get(schemeName)).transformAndConcat(targetNodeToPBXTargetTransformer);
        if (isMainScheme) {
            orderedBuildTestTargets = orderedBuildTestTargets.append(synthesizedCombinedTestTargets);
        }//from  ww w .j a  v a  2 s  .co m
        FluentIterable<PBXTarget> orderedRunTestTargets = FluentIterable.from(ungroupedTests.get(schemeName))
                .transformAndConcat(targetNodeToPBXTargetTransformer);
        if (isMainScheme) {
            orderedRunTestTargets = orderedRunTestTargets.append(synthesizedCombinedTestTargets);
        }
        Optional<String> runnablePath;
        Optional<BuildTarget> targetToBuildWithBuck = getTargetToBuildWithBuck();
        if (buildWithBuck && targetToBuildWithBuck.isPresent()) {
            Optional<String> productName = getProductName(schemeNameToSrcTargetNode.get(schemeName),
                    targetToBuildWithBuck);
            String binaryName = AppleBundle.getBinaryName(targetToBuildWithBuck.get(), productName);
            runnablePath = Optional.of(projectFilesystem.resolve(
                    ProjectGenerator.getScratchPathForAppBundle(targetToBuildWithBuck.get(), binaryName))
                    .toString());
        } else {
            runnablePath = Optional.absent();
        }
        Optional<String> remoteRunnablePath;
        if (schemeConfigArg.isRemoteRunnable.or(false)) {
            // XXX TODO(bhamiltoncx): Figure out the actual name of the binary to launch
            remoteRunnablePath = Optional.of("/" + workspaceName);
        } else {
            remoteRunnablePath = Optional.absent();
        }
        SchemeGenerator schemeGenerator = new SchemeGenerator(projectFilesystem,
                schemeConfigArg.srcTarget.transform(buildTargetToPBXTargetTransformer), orderedBuildTargets,
                orderedBuildTestTargets, orderedRunTestTargets, schemeName,
                combinedProject ? outputDirectory : outputDirectory.resolve(workspaceName + ".xcworkspace"),
                buildWithBuck, parallelizeBuild, runnablePath, remoteRunnablePath,
                XcodeWorkspaceConfigDescription.getActionConfigNamesFromArg(workspaceArguments),
                targetToProjectPathMap);
        schemeGenerator.writeScheme();
        schemeGenerators.put(schemeName, schemeGenerator);
    }
}

From source file:com.eucalyptus.bootstrap.Hosts.java

static List<String> getHostDatabaseErrors(final Host coordinator, final List<Host> hosts) {
    final List<String> errors = Lists.newArrayList();
    if (coordinator != null) {
        final List<DBStatus> distinctStatus = CollectionUtils.reduce(coordinator.getDatabaseStatus(),
                Lists.<DBStatus>newArrayList(), distinctStatus());
        final Iterable<String> coordinatorErrors = Optional.presentInstances(
                Iterables.transform(coordinator.getDatabaseStatus(), DbStatusErrorTransform.INSTANCE));
        if (distinctStatus.size() > 1 || !Iterables.isEmpty(coordinatorErrors)) {
            if (distinctStatus.size() > 1) {
                errors.add(String.format("Host %s database error: Inconsistent primary/secondary databases %s",
                        coordinator.getDisplayName(), distinctStatus));
            }//from  www.ja  v a2s.c om

            // report per-host errors since we can't check for consistency against invalid primary
            for (final Host host : Iterables.filter(hosts, DbStatusErrorFilter.INSTANCE)) {
                for (final String error : Optional.presentInstances(
                        Iterables.transform(host.getDatabaseStatus(), DbStatusErrorTransform.INSTANCE))) {
                    errors.add(String.format("Host %s database error: %s", host.getDisplayName(), error));
                }
            }
        } else if (distinctStatus.size() == 1)
            for (final Host host : hosts) {
                final List<DBStatus> inconsistentStatus = Lists.newArrayList(Iterables.filter(
                        host.getDatabaseStatus(), Predicates.not(consistentWith(distinctStatus.get(0)))));
                if (!inconsistentStatus.isEmpty()) {
                    errors.add(
                            String.format("Host %s database error: Inconsistent primary/secondary databases %s",
                                    host.getDisplayName(), inconsistentStatus));
                }
            }
    }
    return errors;
}