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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:omero.cmd.graphs.ChildOptionI.java

/**
 * Initialize this child option instance.
 * An option takes effect according to the {@link ChildOption} field values set when this method was last called.
 *//*w w  w.  java2s.com*/
public void init() {
    /* convert the class names to actual classes */

    final Function<String, Class<? extends IObject>> getClassFromName = new Function<String, Class<? extends IObject>>() {
        @Override
        public Class<? extends IObject> apply(String className) {
            final int lastDot = className.lastIndexOf('.');
            if (lastDot > 0) {
                className = className.substring(lastDot + 1);
            }
            return graphPathBean.getClassForSimpleName(className);
        }
    };

    /* construct the function corresponding to the type-based inclusion requirements */

    final ImmutableSet<Class<? extends IObject>> typeInclusions;
    final ImmutableSet<Class<? extends IObject>> typeExclusions;

    if (CollectionUtils.isEmpty(includeType)) {
        typeInclusions = ImmutableSet.of();
    } else {
        typeInclusions = ImmutableSet.copyOf(Collections2.transform(includeType, getClassFromName));
    }
    if (CollectionUtils.isEmpty(excludeType)) {
        typeExclusions = ImmutableSet.of();
    } else {
        typeExclusions = ImmutableSet.copyOf(Collections2.transform(excludeType, getClassFromName));
    }

    if (typeInclusions.isEmpty() && typeExclusions.isEmpty()) {
        throw new IllegalArgumentException("child option must include or exclude some type");
    }

    isIncludeType = new Function<Class<? extends IObject>, Boolean>() {
        @Override
        public Boolean apply(Class<? extends IObject> objectClass) {
            for (final Class<? extends IObject> typeInclusion : typeInclusions) {
                if (typeInclusion.isAssignableFrom(objectClass)) {
                    return Boolean.TRUE;
                }
            }
            for (final Class<? extends IObject> typeExclusion : typeExclusions) {
                if (typeExclusion.isAssignableFrom(objectClass)) {
                    return Boolean.FALSE;
                }
            }
            return null;
        }
    };

    /* if no annotation namespaces are set, then apply the defaults */

    if (CollectionUtils.isEmpty(includeNs) && CollectionUtils.isEmpty(excludeNs)) {
        excludeNs = new ArrayList<String>(defaultExcludeNs);
    }

    /* construct the predicate corresponding to the namespace restriction */

    if (CollectionUtils.isEmpty(includeNs)) {
        if (CollectionUtils.isEmpty(excludeNs)) {
            /* there is no adjustment to make, not even for any default namespaces */
            isTargetNamespace = Predicates.alwaysTrue();
        } else {
            final ImmutableSet<String> nsExclusions = ImmutableSet.copyOf(excludeNs);
            isTargetNamespace = new Predicate<String>() {
                @Override
                public boolean apply(String namespace) {
                    return !nsExclusions.contains(namespace);
                }
            };
        }
    } else {
        if (CollectionUtils.isEmpty(excludeNs)) {
            final ImmutableSet<String> nsInclusions = ImmutableSet.copyOf(includeNs);
            isTargetNamespace = new Predicate<String>() {
                @Override
                public boolean apply(String namespace) {
                    return nsInclusions.contains(namespace);
                }
            };
        } else {
            throw new IllegalArgumentException("child option may not both include and exclude namespace");
        }
    }
}

From source file:com.facebook.buck.apple.project_generator.XCodeProjectCommandHelper.java

/** Run xcode specific project generation actions. */
private int runXcodeProjectGenerator(ListeningExecutorService executor,
        final TargetGraphAndTargets targetGraphAndTargets, ImmutableSet<BuildTarget> passedInTargetsSet)
        throws IOException, InterruptedException {
    int exitCode = 0;
    AppleConfig appleConfig = buckConfig.getView(AppleConfig.class);
    ImmutableSet<ProjectGenerator.Option> options = buildWorkspaceGeneratorOptions(readOnly,
            isWithTests(buckConfig), isWithDependenciesTests(buckConfig), combinedProject,
            appleConfig.shouldUseHeaderMapsInXcodeProject(), appleConfig.shouldMergeHeaderMapsInXcodeProject(),
            appleConfig.shouldGenerateHeaderSymlinkTreesOnly());

    ImmutableSet<BuildTarget> requiredBuildTargets = generateWorkspacesForTargets(buckEventBus, cell,
            buckConfig, executorService, targetGraphAndTargets, passedInTargetsSet, options,
            getFocusModules(executor), new HashMap<>(), combinedProject);
    if (!requiredBuildTargets.isEmpty()) {
        ImmutableMultimap<Path, String> cellPathToCellName = cell.getCellPathResolver().getCellPaths()
                .asMultimap().inverse();
        ImmutableList<String> arguments = RichStream.from(requiredBuildTargets).map(target -> {
            if (!target.getCellPath().equals(cell.getRoot())) {
                Optional<String> cellName = cellPathToCellName.get(target.getCellPath()).stream().findAny();
                if (cellName.isPresent()) {
                    return target.withUnflavoredBuildTarget(UnflavoredBuildTarget.of(target.getCellPath(),
                            cellName, target.getBaseName(), target.getShortName()));
                } else {
                    throw new IllegalStateException(
                            "Failed to find cell name for cell path while constructing parameters to "
                                    + "build dependencies for project generation. " + "Build target: " + target
                                    + " cell path: " + target.getCellPath());
                }/*from w  ww. jav a 2  s  .  com*/
            } else {
                return target;
            }
        }).map(Object::toString).toImmutableList();
        exitCode = buildRunner.apply(arguments);
    }
    return exitCode;
}

From source file:com.facebook.buck.android.CopyNativeLibraries.java

protected CopyNativeLibraries(BuildRuleParams buildRuleParams, ImmutableSet<SourcePath> nativeLibDirectories,
        ImmutableSet<StrippedObjectDescription> stripLibRules,
        ImmutableSet<StrippedObjectDescription> stripLibAssetRules, ImmutableSet<TargetCpuType> cpuFilters,
        String moduleName) {/*from  w w  w .  jav a 2 s. co  m*/
    super(buildRuleParams);
    this.nativeLibDirectories = nativeLibDirectories;
    this.stripLibRules = stripLibRules;
    this.stripLibAssetRules = stripLibAssetRules;
    this.cpuFilters = cpuFilters;
    this.moduleName = moduleName;
    Preconditions.checkArgument(
            !nativeLibDirectories.isEmpty() || !stripLibRules.isEmpty() || !stripLibAssetRules.isEmpty(),
            "There should be at least one native library to copy.");
}

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

private void addResourcesFileReference(PBXGroup targetGroup, ImmutableSet<Path> resourceFiles,
        ImmutableSet<Path> resourceDirs, ImmutableSet<Path> variantResourceFiles,
        Function<? super PBXFileReference, Void> resourceCallback,
        Function<? super PBXVariantGroup, Void> variantGroupCallback) {
    if (resourceFiles.isEmpty() && resourceDirs.isEmpty() && variantResourceFiles.isEmpty()) {
        return;/*  www .j a v a  2 s .c  o m*/
    }

    PBXGroup resourcesGroup = targetGroup.getOrCreateChildGroupByName("Resources");
    for (Path path : resourceFiles) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.<String>absent()));
        resourceCallback.apply(fileReference);
    }
    for (Path path : resourceDirs) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.of("folder")));
        resourceCallback.apply(fileReference);
    }

    Map<String, PBXVariantGroup> variantGroups = Maps.newHashMap();
    for (Path variantFilePath : variantResourceFiles) {
        String lprojSuffix = ".lproj";
        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(lprojSuffix)) {
            throw new HumanReadableException(
                    "Variant files have to be in a directory with name ending in '.lproj', "
                            + "but '%s' is not.",
                    variantFilePath);
        }
        String variantDirectoryName = variantDirectory.getFileName().toString();
        String variantLocalization = variantDirectoryName.substring(0,
                variantDirectoryName.length() - lprojSuffix.length());
        String variantFileName = variantFilePath.getFileName().toString();
        PBXVariantGroup variantGroup = variantGroups.get(variantFileName);
        if (variantGroup == null) {
            variantGroup = resourcesGroup.getOrCreateChildVariantGroupByName(variantFileName);
            variantGroupCallback.apply(variantGroup);
            variantGroups.put(variantFileName, variantGroup);
        }
        SourceTreePath sourceTreePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                pathRelativizer.outputDirToRootRelative(variantFilePath), Optional.<String>absent());
        variantGroup.getOrCreateVariantFileReferenceByNameAndSourceTreePath(variantLocalization,
                sourceTreePath);
    }
}

From source file:com.facebook.buck.apple.project_generator.NewNativeTargetProjectMutator.java

private void addResourcesFileReference(PBXGroup targetGroup, ImmutableSet<Path> resourceFiles,
        ImmutableSet<Path> resourceDirs, ImmutableSet<Path> variantResourceFiles,
        Consumer<? super PBXFileReference> resourceCallback,
        Consumer<? super PBXVariantGroup> variantGroupCallback) {
    if (resourceFiles.isEmpty() && resourceDirs.isEmpty() && variantResourceFiles.isEmpty()) {
        return;//from w w w.  j  a va  2s.  c om
    }

    PBXGroup resourcesGroup = targetGroup.getOrCreateChildGroupByName("Resources");
    for (Path path : resourceFiles) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.empty()));
        resourceCallback.accept(fileReference);
    }
    for (Path path : resourceDirs) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.of("folder")));
        resourceCallback.accept(fileReference);
    }

    Map<String, PBXVariantGroup> variantGroups = Maps.newHashMap();
    for (Path variantFilePath : variantResourceFiles) {
        String lprojSuffix = ".lproj";
        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(lprojSuffix)) {
            throw new HumanReadableException(
                    "Variant files have to be in a directory with name ending in '.lproj', "
                            + "but '%s' is not.",
                    variantFilePath);
        }
        String variantDirectoryName = variantDirectory.getFileName().toString();
        String variantLocalization = variantDirectoryName.substring(0,
                variantDirectoryName.length() - lprojSuffix.length());
        String variantFileName = variantFilePath.getFileName().toString();
        PBXVariantGroup variantGroup = variantGroups.get(variantFileName);
        if (variantGroup == null) {
            variantGroup = resourcesGroup.getOrCreateChildVariantGroupByName(variantFileName);
            variantGroupCallback.accept(variantGroup);
            variantGroups.put(variantFileName, variantGroup);
        }
        SourceTreePath sourceTreePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                pathRelativizer.outputDirToRootRelative(variantFilePath), Optional.empty());
        variantGroup.getOrCreateVariantFileReferenceByNameAndSourceTreePath(variantLocalization,
                sourceTreePath);
    }
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

/**
 * Returns whether the given dependency path would require the most recent request to be resolved
 * by only provision bindings./*from w  ww . jav a 2  s.c o  m*/
 */
private boolean doesPathRequireProvisionOnly(Deque<ResolvedRequest> path) {
    if (path.size() == 1) {
        // if this is an entry-point, then we check the request
        switch (path.peek().request().kind()) {
        case INSTANCE:
        case PROVIDER:
        case LAZY:
        case MEMBERS_INJECTOR:
            return true;
        case PRODUCER:
        case PRODUCED:
        case FUTURE:
            return false;
        default:
            throw new AssertionError();
        }
    }
    // otherwise, the second-most-recent bindings determine whether the most recent one must be a
    // provision
    ImmutableSet<ProvisionBinding> dependentProvisions = provisionsDependingOnLatestRequest(path);
    return !dependentProvisions.isEmpty();
}

From source file:dagger2.internal.codegen.BindingGraphValidator.java

/**
 * Validates that the scope (if any) of this component are compatible with the scopes of the
 * bindings available in this component// w  w w.  ja v a 2 s.  c  o m
 */
void validateComponentScope(final BindingGraph subject,
        final ValidationReport.Builder<BindingGraph> reportBuilder,
        ImmutableMap<BindingKey, ResolvedBindings> resolvedBindings) {
    Optional<Equivalence.Wrapper<AnnotationMirror>> componentScope = subject.componentDescriptor()
            .wrappedScope();
    ImmutableSet.Builder<String> incompatiblyScopedMethodsBuilder = ImmutableSet.builder();
    for (ResolvedBindings bindings : resolvedBindings.values()) {
        if (bindings.bindingKey().kind().equals(BindingKey.Kind.CONTRIBUTION)) {
            for (ContributionBinding contributionBinding : bindings.ownedContributionBindings()) {
                if (contributionBinding instanceof ProvisionBinding) {
                    ProvisionBinding provisionBinding = (ProvisionBinding) contributionBinding;
                    if (provisionBinding.scope().isPresent()
                            && !componentScope.equals(provisionBinding.wrappedScope())) {
                        // Scoped components cannot reference bindings to @Provides methods or @Inject
                        // types decorated by a different scope annotation. Unscoped components cannot
                        // reference to scoped @Provides methods or @Inject types decorated by any
                        // scope annotation.
                        switch (provisionBinding.bindingKind()) {
                        case PROVISION:
                            ExecutableElement provisionMethod = MoreElements
                                    .asExecutable(provisionBinding.bindingElement());
                            incompatiblyScopedMethodsBuilder
                                    .add(methodSignatureFormatter.format(provisionMethod));
                            break;
                        case INJECTION:
                            incompatiblyScopedMethodsBuilder
                                    .add(stripCommonTypePrefixes(provisionBinding.scope().get().toString())
                                            + " class "
                                            + provisionBinding.bindingTypeElement().getQualifiedName());
                            break;
                        default:
                            throw new IllegalStateException();
                        }
                    }
                }
            }
        }
    }
    ImmutableSet<String> incompatiblyScopedMethods = incompatiblyScopedMethodsBuilder.build();
    if (!incompatiblyScopedMethods.isEmpty()) {
        TypeElement componentType = subject.componentDescriptor().componentDefinitionType();
        StringBuilder message = new StringBuilder(componentType.getQualifiedName());
        if (componentScope.isPresent()) {
            message.append(" scoped with ");
            message.append(stripCommonTypePrefixes(ErrorMessages.format(componentScope.get().get())));
            message.append(" may not reference bindings with different scopes:\n");
        } else {
            message.append(" (unscoped) may not reference scoped bindings:\n");
        }
        for (String method : incompatiblyScopedMethods) {
            message.append(ErrorMessages.INDENT).append(method).append("\n");
        }
        reportBuilder.addItem(message.toString(), componentType,
                subject.componentDescriptor().componentAnnotation());
    }
}

From source file:com.google.devtools.build.lib.server.GrpcServerImpl.java

private void startSlowInterruptWatcher(final ImmutableSet<String> commandIds) {
    if (commandIds.isEmpty()) {
        return;//w  ww .  j a va  2  s. c  o  m
    }

    Runnable interruptWatcher = new Runnable() {
        @Override
        public void run() {
            try {
                boolean ok;
                Thread.sleep(10 * 1000);
                synchronized (runningCommands) {
                    ok = Collections.disjoint(commandIds, runningCommands.keySet());
                }
                if (!ok) {
                    // At least one command was not interrupted. Interrupt took too long.
                    ThreadUtils.warnAboutSlowInterrupt();
                }
            } catch (InterruptedException e) {
                // Ignore.
            }
        }
    };

    Thread interruptWatcherThread = new Thread(interruptWatcher,
            "interrupt-watcher-" + interruptCounter.incrementAndGet());
    interruptWatcherThread.setDaemon(true);
    interruptWatcherThread.start();
}

From source file:com.facebook.buck.cli.TargetsCommand.java

@Override
int runCommandWithOptionsInternal(TargetsCommandOptions options) throws IOException {
    // Exit early if --resolvealias is passed in: no need to parse any build files.
    if (options.isResolveAlias()) {
        return doResolveAlias(options);
    }//w  w  w .  j  a va2 s  .  co  m

    // Verify the --type argument.
    ImmutableSet<String> types = options.getTypes();
    ImmutableSet.Builder<BuildRuleType> buildRuleTypesBuilder = ImmutableSet.builder();
    for (String name : types) {
        try {
            buildRuleTypesBuilder.add(getBuildRuleTypes().getBuildRuleType(name));
        } catch (IllegalArgumentException e) {
            console.printBuildFailure("Invalid build rule type: " + name);
            return 1;
        }
    }

    // Find the build targets that match the specified options.
    ImmutableSet<BuildTarget> matchingBuildTargets;
    try {
        matchingBuildTargets = ImmutableSet
                .copyOf(getBuildTargets(options.getArgumentsFormattedAsBuildTargets()));
    } catch (NoSuchBuildTargetException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    // Parse the entire dependency graph, or (if targets are specified),
    // only the specified targets and their dependencies..
    PartialGraph graph;
    try {
        if (matchingBuildTargets.isEmpty()) {
            graph = PartialGraph.createFullGraph(getProjectFilesystem(), options.getDefaultIncludes(),
                    getParser(), getBuckEventBus());
        } else {
            graph = PartialGraph.createPartialGraphIncludingRoots(matchingBuildTargets,
                    options.getDefaultIncludes(), getParser(), getBuckEventBus());
        }
    } catch (BuildTargetException | BuildFileParseException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    SortedMap<String, BuildRule> matchingBuildRules = getMatchingBuildRules(graph.getDependencyGraph(),
            new TargetsCommandPredicate(graph, buildRuleTypesBuilder.build(),
                    options.getReferencedFiles(getProjectFilesystem().getProjectRoot()), matchingBuildTargets));

    // Print out matching targets in alphabetical order.
    if (options.getPrintJson()) {
        try {
            printJsonForTargets(matchingBuildRules, options.getDefaultIncludes());
        } catch (BuildFileParseException e) {
            console.printBuildFailureWithoutStacktrace(e);
            return 1;
        }
    } else {
        printTargetsList(matchingBuildRules, options.isShowOutput(), options.isShowRuleKey());
    }

    return 0;
}

From source file:com.facebook.buck.features.apple.project.NewNativeTargetProjectMutator.java

private void addResourcesFileReference(PBXGroup targetGroup, ImmutableSet<Path> resourceFiles,
        ImmutableSet<Path> resourceDirs, ImmutableSet<Path> variantResourceFiles,
        Consumer<? super PBXFileReference> resourceCallback,
        Consumer<? super PBXVariantGroup> variantGroupCallback) {
    if (resourceFiles.isEmpty() && resourceDirs.isEmpty() && variantResourceFiles.isEmpty()) {
        return;/*from  ww w. j  av  a2 s.c o m*/
    }

    PBXGroup resourcesGroup = targetGroup.getOrCreateChildGroupByName("Resources");
    for (Path path : resourceFiles) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.empty()));
        resourceCallback.accept(fileReference);
    }
    for (Path path : resourceDirs) {
        PBXFileReference fileReference = resourcesGroup.getOrCreateFileReferenceBySourceTreePath(
                new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                        pathRelativizer.outputDirToRootRelative(path), Optional.of("folder")));
        resourceCallback.accept(fileReference);
    }

    Map<String, PBXVariantGroup> variantGroups = new HashMap<>();
    for (Path variantFilePath : variantResourceFiles) {
        String lprojSuffix = ".lproj";
        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(lprojSuffix)) {
            throw new HumanReadableException(
                    "Variant files have to be in a directory with name ending in '.lproj', "
                            + "but '%s' is not.",
                    variantFilePath);
        }
        String variantDirectoryName = variantDirectory.getFileName().toString();
        String variantLocalization = variantDirectoryName.substring(0,
                variantDirectoryName.length() - lprojSuffix.length());
        String variantFileName = variantFilePath.getFileName().toString();
        PBXVariantGroup variantGroup = variantGroups.get(variantFileName);
        if (variantGroup == null) {
            variantGroup = resourcesGroup.getOrCreateChildVariantGroupByName(variantFileName);
            variantGroupCallback.accept(variantGroup);
            variantGroups.put(variantFileName, variantGroup);
        }
        SourceTreePath sourceTreePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                pathRelativizer.outputDirToRootRelative(variantFilePath), Optional.empty());
        variantGroup.getOrCreateVariantFileReferenceByNameAndSourceTreePath(variantLocalization,
                sourceTreePath);
    }
}