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:com.facebook.buck.io.ProjectFilesystem.java

private static Path getCacheDir(Path root, Optional<String> value, BuckPaths buckPaths) {
    String cacheDir = value.orElse(root.resolve(buckPaths.getCacheDir()).toString());
    Path toReturn = root.getFileSystem().getPath(cacheDir);
    toReturn = MorePaths.expandHomeDir(toReturn);
    if (toReturn.isAbsolute()) {
        return toReturn;
    }/*from  w  w w. java 2  s .  c o  m*/
    ImmutableSet<Path> filtered = MorePaths.filterForSubpaths(ImmutableSet.of(toReturn), root);
    if (filtered.isEmpty()) {
        // OK. For some reason the relative path managed to be out of our directory.
        return toReturn;
    }
    return Iterables.getOnlyElement(filtered);
}

From source file:com.google.auto.factory.processor.FactoryDescriptorGenerator.java

ImmutableSet<FactoryMethodDescriptor> generateDescriptor(Element element) {
    final AnnotationMirror mirror = Mirrors.getAnnotationMirror(element, AutoFactory.class).get();
    final Optional<AutoFactoryDeclaration> declaration = declarationFactory.createIfValid(element);
    if (!declaration.isPresent()) {
        return ImmutableSet.of();
    }/* www .ja va2s.  c om*/
    return element.accept(new ElementKindVisitor6<ImmutableSet<FactoryMethodDescriptor>, Void>() {
        @Override
        protected ImmutableSet<FactoryMethodDescriptor> defaultAction(Element e, Void p) {
            throw new AssertionError("@AutoFactory applied to an impossible element");
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitTypeAsClass(TypeElement type, Void p) {
            if (type.getModifiers().contains(ABSTRACT)) {
                // applied to an abstract factory
                messager.printMessage(ERROR, "Auto-factory doesn't support being applied to abstract classes.",
                        type, mirror);
                return ImmutableSet.of();
            } else {
                // applied to the type to be created
                ImmutableSet<ExecutableElement> constructors = Elements2.getConstructors(type);
                if (constructors.isEmpty()) {
                    return generateDescriptorForDefaultConstructor(declaration.get(), type);
                } else {
                    return FluentIterable.from(constructors)
                            .transform(new Function<ExecutableElement, FactoryMethodDescriptor>() {
                                @Override
                                public FactoryMethodDescriptor apply(ExecutableElement constructor) {
                                    return generateDescriptorForConstructor(declaration.get(), constructor);
                                }
                            }).toSet();
                }
            }
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitTypeAsInterface(TypeElement type, Void p) {
            // applied to the factory interface
            messager.printMessage(ERROR, "Auto-factory doesn't support being applied to interfaces.", type,
                    mirror);
            return ImmutableSet.of();
        }

        @Override
        public ImmutableSet<FactoryMethodDescriptor> visitExecutableAsConstructor(ExecutableElement e, Void p) {
            // applied to a constructor of a type to be created
            return ImmutableSet.of(generateDescriptorForConstructor(declaration.get(), e));
        }
    }, null);
}

From source file:com.github.rinde.rinsim.core.model.DependencyResolver.java

void addDefaultModels() {
    for (final ModelBuilder<?, ?> b : defaultModels) {
        final ImmutableSet<Class<?>> providingTypes = b.getProvidingTypes();
        if (providingTypes.isEmpty() || !providerMap.keySet().containsAll(providingTypes)) {
            checkArgument(Sets.intersection(providerMap.keySet(), providingTypes).isEmpty());
            add(b);/*w  ww.j av a 2 s .  c  om*/
        }
    }
}

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

@Override
@SuppressWarnings("PMD.PrematureDeclaration")
int runCommandWithOptionsInternal(BuildCommandOptions options) throws IOException {
    // Set the logger level based on the verbosity option.
    Verbosity verbosity = console.getVerbosity();
    Logging.setLoggingLevelForVerbosity(verbosity);

    // Create artifact cache to initialize Cassandra connection, if appropriate.
    ArtifactCache artifactCache = getArtifactCache();

    try {/*from ww w. ja v a  2  s. c  o m*/
        buildTargets = getBuildTargets(options.getArgumentsFormattedAsBuildTargets());
    } catch (NoSuchBuildTargetException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    if (buildTargets.isEmpty()) {
        console.printBuildFailure("Must specify at least one build target.");

        // If there are aliases defined in .buckconfig, suggest that the user
        // build one of them. We show the user only the first 10 aliases.
        ImmutableSet<String> aliases = options.getBuckConfig().getAliases();
        if (!aliases.isEmpty()) {
            console.getStdErr().println(String.format("Try building one of the following targets:\n%s",
                    Joiner.on(' ').join(Iterators.limit(aliases.iterator(), 10))));
        }
        return 1;
    }

    // Post the build started event, setting it to the Parser recorded start time if appropriate.
    if (getParser().getParseStartTime().isPresent()) {
        getBuckEventBus().post(BuildEvent.started(buildTargets), getParser().getParseStartTime().get());
    } else {
        getBuckEventBus().post(BuildEvent.started(buildTargets));
    }

    // Parse the build files to create a DependencyGraph.
    DependencyGraph dependencyGraph;
    try {
        dependencyGraph = getParser().parseBuildFilesForTargets(buildTargets, options.getDefaultIncludes(),
                getBuckEventBus());
    } catch (BuildTargetException | BuildFileParseException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    // Create and execute the build.
    build = options.createBuild(options.getBuckConfig(), dependencyGraph, getProjectFilesystem(),
            getAndroidDirectoryResolver(), getBuildEngine(), artifactCache, console, getBuckEventBus(),
            Optional.<TargetDevice>absent(), getCommandRunnerParams().getPlatform());
    int exitCode = 0;
    try {
        exitCode = executeBuildAndPrintAnyFailuresToConsole(build, console);
    } finally {
        build.close(); // Can't use try-with-resources as build is returned by getBuild.
    }
    getBuckEventBus().post(BuildEvent.finished(buildTargets, exitCode));
    return exitCode;
}

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

@Override
public int runWithoutHelp(final CommandRunnerParams params) throws IOException, InterruptedException {
    final ImmutableSet<String> fullyQualifiedBuildTargets = ImmutableSet
            .copyOf(getArgumentsFormattedAsBuildTargets(params.getBuckConfig()));

    if (fullyQualifiedBuildTargets.isEmpty()) {
        params.getBuckEventBus().post(ConsoleEvent.severe("Must specify at least one build target."));
        return 1;
    }//from  ww  w.j av a  2  s.  com

    if (params.getConsole().getAnsi().isAnsiTerminal()) {
        params.getBuckEventBus().post(ConsoleEvent.info(
                "'buck audit dependencies' is deprecated. Please use 'buck query' instead.\n"
                        + "The equivalent 'buck query' command is:\n$ %s\n\nThe query language is documented at "
                        + "https://buckbuild.com/command/query.html",
                QueryCommand.buildAuditDependenciesQueryExpression(getArguments(),
                        shouldShowTransitiveDependencies(), shouldIncludeTests(), shouldGenerateJsonOutput())));
    }

    try (CommandThreadManager pool = new CommandThreadManager("Audit",
            getConcurrencyLimit(params.getBuckConfig()));
            PerBuildState parserState = new PerBuildState(params.getParser(), params.getBuckEventBus(),
                    pool.getExecutor(), params.getCell(), getEnableParserProfiling(),
                    SpeculativeParsing.of(true), /* ignoreBuckAutodepsFiles */ false)) {
        BuckQueryEnvironment env = BuckQueryEnvironment.from(params, parserState, getEnableParserProfiling());
        return QueryCommand.runMultipleQuery(params, env, pool.getExecutor(),
                QueryCommand.getAuditDependenciesQueryFormat(shouldShowTransitiveDependencies(),
                        shouldIncludeTests()),
                getArgumentsFormattedAsBuildTargets(params.getBuckConfig()), shouldGenerateJsonOutput());
    } catch (Exception e) {
        if (e.getCause() instanceof InterruptedException) {
            throw (InterruptedException) e.getCause();
        }
        params.getBuckEventBus()
                .post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
        return 1;
    }
}

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

@Override
int runCommandWithOptionsInternal(AuditCommandOptions options) throws IOException {
    // Create a PartialGraph that is composed of the transitive closure of all of the dependent
    // BuildRules for the specified BuildTargets.
    final ImmutableSet<String> fullyQualifiedBuildTargets = ImmutableSet
            .copyOf(options.getArgumentsFormattedAsBuildTargets());

    if (fullyQualifiedBuildTargets.isEmpty()) {
        console.printBuildFailure("Please specify at least one build target.");
        return 1;
    }/*from w  w w  .  ja  v a2  s  . co  m*/

    RawRulePredicate predicate = new RawRulePredicate() {
        @Override
        public boolean isMatch(Map<String, Object> rawParseData, BuildRuleType buildRuleType,
                BuildTarget buildTarget) {
            return fullyQualifiedBuildTargets.contains(buildTarget.getFullyQualifiedName());
        }
    };
    PartialGraph partialGraph;
    try {
        partialGraph = PartialGraph.createPartialGraph(predicate, getProjectFilesystem(),
                options.getDefaultIncludes(), getParser(), getBuckEventBus());
    } catch (BuildTargetException | BuildFileParseException e) {
        console.printBuildFailureWithoutStacktrace(e);
        return 1;
    }

    if (options.shouldGenerateJsonOutput()) {
        return printJsonInputs(partialGraph);
    }
    return printInputs(partialGraph);
}

From source file:com.google.errorprone.bugpatterns.InconsistentCapitalization.java

@Override
public Description matchClass(ClassTree tree, VisitorState state) {
    ImmutableSet<Symbol> fields = FieldScanner.findFields(tree);

    if (fields.isEmpty()) {
        return Description.NO_MATCH;
    }//from w w  w . j a v a2s  .com

    ImmutableMap<String, Symbol> fieldNamesMap = fields.stream()
            .collect(toImmutableMap(symbol -> Ascii.toLowerCase(symbol.toString()), x -> x, (x, y) -> x));
    ImmutableMap<TreePath, Symbol> matchedParameters = MatchingParametersScanner
            .findMatchingParameters(fieldNamesMap, state.getPath());

    if (matchedParameters.isEmpty()) {
        return Description.NO_MATCH;
    }

    for (Entry<TreePath, Symbol> entry : matchedParameters.entrySet()) {
        TreePath parameterPath = entry.getKey();
        Symbol field = entry.getValue();
        String fieldName = field.getSimpleName().toString();
        VariableTree parameterTree = (VariableTree) parameterPath.getLeaf();
        SuggestedFix.Builder fix = SuggestedFix.builder()
                .merge(SuggestedFixes.renameVariable(parameterTree, fieldName, state));

        if (parameterPath.getParentPath() != null) {
            String qualifiedName = getExplicitQualification(parameterPath, tree, state) + field.getSimpleName();
            // If the field was accessed in a non-qualified way, by renaming the parameter this may
            // cause clashes with it. Thus, it is required to qualify all uses of the field within the
            // parameter's scope just in case.
            parameterPath.getParentPath().getLeaf().accept(new TreeScanner<Void, Void>() {
                @Override
                public Void visitIdentifier(IdentifierTree tree, Void unused) {
                    if (field.equals(ASTHelpers.getSymbol(tree))) {
                        fix.replace(tree, qualifiedName);
                    }
                    return null;
                }
            }, null);
        }
        state.reportMatch(
                buildDescription(parameterPath.getLeaf())
                        .setMessage(String.format(
                                "Found the field '%s' with the same name as the parameter '%s' but with "
                                        + "different capitalization.",
                                fieldName, ((VariableTree) parameterPath.getLeaf()).getName()))
                        .addFix(fix.build()).build());
    }

    return Description.NO_MATCH;
}

From source file:com.facebook.buck.features.python.PythonInPlaceBinary.java

private static Supplier<String> getScript(BuildRuleResolver resolver, PythonPlatform pythonPlatform,
        CxxPlatform cxxPlatform, String mainModule, PythonPackageComponents components,
        Path relativeLinkTreeRoot, ImmutableSet<String> preloadLibraries, PackageStyle packageStyle) {
    String relativeLinkTreeRootStr = Escaper.escapeAsPythonString(relativeLinkTreeRoot.toString());
    Linker ld = cxxPlatform.getLd().resolve(resolver);
    return () -> {
        ST st = new ST(
                packageStyle == PackageStyle.INPLACE ? getRunInplaceResource() : getRunInplaceLiteResource())
                        .add("PYTHON", pythonPlatform.getEnvironment().getPythonPath())
                        .add("MAIN_MODULE", Escaper.escapeAsPythonString(mainModule))
                        .add("MODULES_DIR", relativeLinkTreeRootStr);

        // Only add platform-specific values when the binary includes native libraries.
        if (components.getNativeLibraries().isEmpty()) {
            st.add("NATIVE_LIBS_ENV_VAR", "None");
            st.add("NATIVE_LIBS_DIR", "None");
        } else {//from   www.j  a v a2  s  . co m
            st.add("NATIVE_LIBS_ENV_VAR", Escaper.escapeAsPythonString(ld.searchPathEnvVar()));
            st.add("NATIVE_LIBS_DIR", relativeLinkTreeRootStr);
        }

        if (preloadLibraries.isEmpty()) {
            st.add("NATIVE_LIBS_PRELOAD_ENV_VAR", "None");
            st.add("NATIVE_LIBS_PRELOAD", "None");
        } else {
            st.add("NATIVE_LIBS_PRELOAD_ENV_VAR", Escaper.escapeAsPythonString(ld.preloadEnvVar()));
            st.add("NATIVE_LIBS_PRELOAD", Escaper.escapeAsPythonString(Joiner.on(':').join(preloadLibraries)));
        }
        return st.render();
    };
}

From source file:com.github.jsdossier.jscomp.NodeLibrary.java

@Inject
NodeLibrary(@ModuleExterns ImmutableSet<Path> userExterns, @Modules ImmutableSet<Path> modulePaths) {
    if (modulePaths.isEmpty()) {
        externs = Suppliers.ofInstance(ExternCollection.empty());
    } else {//from www  .  j  a  v  a2  s . c  o  m
        externs = Suppliers.memoize(new ExternSupplier(userExterns));
    }
}

From source file:com.google.template.soy.passes.CheckCallsVisitor.java

@Override
protected void visitCallNode(CallNode node) {

    // Recurse.//from   w  ww  .  java 2s.  com
    visitChildren(node);

    // If all the data keys being passed are listed using 'param' commands, then check that all
    // required params of the callee are included.
    if (!node.dataAttribute().isPassingData()) {

        // Get the callee node (basic or delegate).
        TemplateNode callee = null;
        if (node instanceof CallBasicNode) {
            callee = templateRegistry.getBasicTemplate(((CallBasicNode) node).getCalleeName());
        } else {
            String delTemplateName = ((CallDelegateNode) node).getDelCalleeName();
            ImmutableSet<DelegateTemplateDivision> divisions = templateRegistry
                    .getDelTemplateDivisionsForAllVariants(delTemplateName);
            if (!divisions.isEmpty()) {
                callee = Iterables
                        .get(Iterables.getFirst(divisions, null).delPackageNameToDelTemplateMap.values(), 0);
            }
        }

        // Do the check if the callee node has declared params.
        if (callee != null && callee.getParams() != null) {
            // Get param keys passed by caller.
            Set<String> callerParamKeys = Sets.newHashSet();
            for (CallParamNode callerParam : node.getChildren()) {
                callerParamKeys.add(callerParam.getKey());
            }
            // Check param keys required by callee.
            List<String> missingParamKeys = Lists.newArrayListWithCapacity(2);
            for (TemplateParam calleeParam : callee.getParams()) {
                if (calleeParam.isRequired() && !callerParamKeys.contains(calleeParam.name())) {
                    missingParamKeys.add(calleeParam.name());
                }
            }
            // Report errors.
            if (!missingParamKeys.isEmpty()) {
                String errorMsgEnd = (missingParamKeys.size() == 1) ? "param '" + missingParamKeys.get(0) + "'"
                        : "params " + missingParamKeys;
                errorReporter.report(node.getSourceLocation(), MISSING_PARAM, errorMsgEnd);
            }
        }
    }
}