List of usage examples for com.google.common.collect ImmutableSet isEmpty
boolean isEmpty();
From source file:org.springframework.ide.eclipse.boot.dash.model.AbstractLaunchConfigurationsDashElement.java
@Override public void openConfig(UserInteractions ui) { try {//from w w w .j a v a2s . c o m IProject p = getProject(); if (p != null) { ILaunchConfiguration conf; ImmutableSet<ILaunchConfiguration> configs = getLaunchConfigs(); if (configs.isEmpty()) { conf = createLaunchConfigForEditing(); } else { conf = chooseConfig(ui, configs); } if (conf != null) { ui.openLaunchConfigurationDialogOnGroup(conf, getLaunchGroup()); } } } catch (Exception e) { ui.errorPopup("Couldn't open config for " + getName(), ExceptionUtil.getMessage(e)); } }
From source file:com.facebook.buck.artifact_cache.SQLiteArtifactCache.java
private ListenableFuture<Void> storeContent(ImmutableSet<RuleKey> contentHashes, BorrowablePath content) { try {// w w w . ja va2 s .c om ImmutableSet<RuleKey> toStore = notPreexisting(contentHashes); if (toStore.isEmpty()) { return Futures.immediateFuture(null); } long size = filesystem.getFileSize(content.getPath()); if (size <= maxInlinedBytes) { // artifact is small enough to inline in the database db.storeArtifact(toStore, Files.readAllBytes(content.getPath()), size); } else if (!toStore.isEmpty()) { // artifact is too large to inline, store on disk and put path in database Path artifactPath = getArtifactPath(toStore.iterator().next()); filesystem.mkdirs(artifactPath.getParent()); if (content.canBorrow()) { filesystem.move(content.getPath(), artifactPath, StandardCopyOption.REPLACE_EXISTING); } else { storeArtifactOutput(content.getPath(), artifactPath); } db.storeFilepath(toStore, artifactPath.toString(), size); } } catch (IOException | SQLException e) { LOG.warn(e, "Artifact store(%s, %s) error", contentHashes, content); } return Futures.immediateFuture(null); }
From source file:com.facebook.buck.features.python.PythonTestDescription.java
@Override public PythonTest createBuildRule(BuildRuleCreationContextWithTargetGraph context, BuildTarget buildTarget, BuildRuleParams params, PythonTestDescriptionArg args) { FlavorDomain<PythonPlatform> pythonPlatforms = toolchainProvider .getByName(PythonPlatformsProvider.DEFAULT_NAME, PythonPlatformsProvider.class) .getPythonPlatforms();// w w w . jav a 2 s . c o m ActionGraphBuilder graphBuilder = context.getActionGraphBuilder(); PythonPlatform pythonPlatform = pythonPlatforms.getValue(buildTarget) .orElse(pythonPlatforms.getValue(args.getPlatform().<Flavor>map(InternalFlavor::of) .orElse(pythonPlatforms.getFlavors().iterator().next()))); CxxPlatform cxxPlatform = getCxxPlatform(buildTarget, args).resolve(graphBuilder); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); Path baseModule = PythonUtil.getBasePath(buildTarget, args.getBaseModule()); Optional<ImmutableMap<BuildTarget, Version>> selectedVersions = context.getTargetGraph().get(buildTarget) .getSelectedVersions(); ImmutableMap<Path, SourcePath> srcs = PythonUtil.getModules(buildTarget, graphBuilder, ruleFinder, pathResolver, pythonPlatform, cxxPlatform, "srcs", baseModule, args.getSrcs(), args.getPlatformSrcs(), args.getVersionedSrcs(), selectedVersions); ImmutableMap<Path, SourcePath> resources = PythonUtil.getModules(buildTarget, graphBuilder, ruleFinder, pathResolver, pythonPlatform, cxxPlatform, "resources", baseModule, args.getResources(), args.getPlatformResources(), args.getVersionedResources(), selectedVersions); // Convert the passed in module paths into test module names. ImmutableSet.Builder<String> testModulesBuilder = ImmutableSet.builder(); for (Path name : srcs.keySet()) { testModulesBuilder.add(PythonUtil.toModuleName(buildTarget, name.toString())); } ImmutableSet<String> testModules = testModulesBuilder.build(); ProjectFilesystem projectFilesystem = context.getProjectFilesystem(); // Construct a build rule to generate the test modules list source file and // add it to the build. BuildRule testModulesBuildRule = createTestModulesSourceBuildRule(buildTarget, projectFilesystem, getTestModulesListPath(buildTarget, projectFilesystem), testModules); graphBuilder.addToIndex(testModulesBuildRule); String mainModule; if (args.getMainModule().isPresent()) { mainModule = args.getMainModule().get(); } else { mainModule = PythonUtil.toModuleName(buildTarget, getTestMainName().toString()); } // Build up the list of everything going into the python test. PythonPackageComponents testComponents = PythonPackageComponents.of( ImmutableMap.<Path, SourcePath>builder() .put(getTestModulesListName(), testModulesBuildRule.getSourcePathToOutput()) .put(getTestMainName(), requireTestMain(buildTarget, projectFilesystem, graphBuilder)) .putAll(srcs).build(), resources, ImmutableMap.of(), ImmutableMultimap.of(), args.getZipSafe()); ImmutableList<BuildRule> deps = RichStream .from(PythonUtil.getDeps(pythonPlatform, cxxPlatform, args.getDeps(), args.getPlatformDeps())) .concat(args.getNeededCoverage().stream().map(NeededCoverageSpec::getBuildTarget)) .map(graphBuilder::getRule).collect(ImmutableList.toImmutableList()); CellPathResolver cellRoots = context.getCellPathResolver(); StringWithMacrosConverter macrosConverter = StringWithMacrosConverter.builder().setBuildTarget(buildTarget) .setCellPathResolver(cellRoots).setExpanders(PythonUtil.MACRO_EXPANDERS).build(); PythonPackageComponents allComponents = PythonUtil.getAllComponents(cellRoots, buildTarget, projectFilesystem, params, graphBuilder, ruleFinder, deps, testComponents, pythonPlatform, cxxBuckConfig, cxxPlatform, args.getLinkerFlags().stream().map(x -> macrosConverter.convert(x, graphBuilder)) .collect(ImmutableList.toImmutableList()), pythonBuckConfig.getNativeLinkStrategy(), args.getPreloadDeps()); // Build the PEX using a python binary rule with the minimum dependencies. buildTarget.assertUnflavored(); PythonBinary binary = binaryDescription.createPackageRule(buildTarget.withAppendedFlavors(BINARY_FLAVOR), projectFilesystem, params, graphBuilder, ruleFinder, pythonPlatform, cxxPlatform, mainModule, args.getExtension(), allComponents, args.getBuildArgs(), args.getPackageStyle().orElse(pythonBuckConfig.getPackageStyle()), PythonUtil.getPreloadNames(graphBuilder, cxxPlatform, args.getPreloadDeps())); graphBuilder.addToIndex(binary); ImmutableList.Builder<Pair<Float, ImmutableSet<Path>>> neededCoverageBuilder = ImmutableList.builder(); for (NeededCoverageSpec coverageSpec : args.getNeededCoverage()) { BuildRule buildRule = graphBuilder.getRule(coverageSpec.getBuildTarget()); if (deps.contains(buildRule) && buildRule instanceof PythonLibrary) { PythonLibrary pythonLibrary = (PythonLibrary) buildRule; ImmutableSortedSet<Path> paths; if (coverageSpec.getPathName().isPresent()) { Path path = coverageSpec.getBuildTarget().getBasePath() .resolve(coverageSpec.getPathName().get()); if (!pythonLibrary.getPythonPackageComponents(pythonPlatform, cxxPlatform, graphBuilder) .getModules().keySet().contains(path)) { throw new HumanReadableException( "%s: path %s specified in needed_coverage not found in target %s", buildTarget, path, buildRule.getBuildTarget()); } paths = ImmutableSortedSet.of(path); } else { paths = ImmutableSortedSet.copyOf( pythonLibrary.getPythonPackageComponents(pythonPlatform, cxxPlatform, graphBuilder) .getModules().keySet()); } neededCoverageBuilder .add(new Pair<>(coverageSpec.getNeededCoverageRatioPercentage() / 100.f, paths)); } else { throw new HumanReadableException( "%s: needed_coverage requires a python library dependency. Found %s instead", buildTarget, buildRule); } } Function<BuildRuleResolver, ImmutableMap<String, Arg>> testEnv = (ruleResolverInner) -> ImmutableMap .copyOf(Maps.transformValues(args.getEnv(), x -> macrosConverter.convert(x, graphBuilder))); // Additional CXX Targets used to generate CXX coverage. ImmutableSet<UnflavoredBuildTarget> additionalCoverageTargets = RichStream .from(args.getAdditionalCoverageTargets()).map(target -> target.getUnflavoredBuildTarget()) .collect(ImmutableSet.toImmutableSet()); ImmutableSortedSet<SourcePath> additionalCoverageSourcePaths = additionalCoverageTargets.isEmpty() ? ImmutableSortedSet.of() : binary.getRuntimeDeps(ruleFinder) .filter(target -> additionalCoverageTargets.contains(target.getUnflavoredBuildTarget())) .map(target -> DefaultBuildTargetSourcePath.of(target)) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())); // Generate and return the python test rule, which depends on the python binary rule above. return PythonTest.from(buildTarget, projectFilesystem, params, graphBuilder, testEnv, binary, args.getLabels(), neededCoverageBuilder.build(), additionalCoverageSourcePaths, args.getTestRuleTimeoutMs().map(Optional::of).orElse( cxxBuckConfig.getDelegate().getView(TestBuckConfig.class).getDefaultTestRuleTimeoutMs()), args.getContacts()); }
From source file:dagger.internal.codegen.ModuleValidator.java
private void validateModuleVisibility(final TypeElement moduleElement, ModuleDescriptor.Kind moduleKind, final ValidationReport.Builder<?> reportBuilder) { Visibility moduleVisibility = Visibility.ofElement(moduleElement); if (moduleVisibility.equals(PRIVATE)) { reportBuilder.addError("Modules cannot be private.", moduleElement); } else if (effectiveVisibilityOfElement(moduleElement).equals(PRIVATE)) { reportBuilder.addError("Modules cannot be enclosed in private types.", moduleElement); }/*from w w w . j a v a 2 s.com*/ switch (moduleElement.getNestingKind()) { case ANONYMOUS: throw new IllegalStateException("Can't apply @Module to an anonymous class"); case LOCAL: throw new IllegalStateException("Local classes shouldn't show up in the processor"); case MEMBER: case TOP_LEVEL: if (moduleVisibility.equals(PUBLIC)) { ImmutableSet<Element> nonPublicModules = FluentIterable .from(getModuleIncludes( getAnnotationMirror(moduleElement, moduleKind.moduleAnnotation()).get())) .transform(types::asElement) .filter(element -> effectiveVisibilityOfElement(element).compareTo(PUBLIC) < 0).toSet(); if (!nonPublicModules.isEmpty()) { reportBuilder.addError(String.format( "This module is public, but it includes non-public " + "(or effectively non-public) modules. " + "Either reduce the visibility of this module or make %s public.", formatListForErrorMessage(nonPublicModules.asList())), moduleElement); } } break; default: throw new AssertionError(); } }
From source file:com.google.devtools.build.lib.skyframe.ConfigurationCollectionFunction.java
/** Create the build configurations with the given options. */ private BuildConfigurationCollection getConfigurations(Environment env, PackageProviderForConfigurations loadedPackageProvider, BuildOptions buildOptions, ImmutableSet<String> multiCpu) throws InvalidConfigurationException, InterruptedException { // We cache all the related configurations for this target configuration in a cache that is // dropped at the end of this method call. We instead rely on the cache for entire collections // for caching the target and related configurations, and on a dedicated host configuration // cache for the host configuration. Cache<String, BuildConfiguration> cache = CacheBuilder.newBuilder().<String, BuildConfiguration>build(); List<BuildConfiguration> targetConfigurations = new ArrayList<>(); if (!multiCpu.isEmpty()) { for (String cpu : multiCpu) { BuildConfiguration targetConfiguration = createConfiguration(cache, env.getListener(), loadedPackageProvider, buildOptions, cpu); if (targetConfiguration == null || targetConfigurations.contains(targetConfiguration)) { continue; }/*from www. j a v a2s . c o m*/ targetConfigurations.add(targetConfiguration); } if (loadedPackageProvider.valuesMissing()) { return null; } } else { BuildConfiguration targetConfiguration = createConfiguration(cache, env.getListener(), loadedPackageProvider, buildOptions, null); if (targetConfiguration == null) { return null; } targetConfigurations.add(targetConfiguration); } BuildConfiguration hostConfiguration = getHostConfiguration(env, targetConfigurations.get(0)); if (hostConfiguration == null) { return null; } return new BuildConfigurationCollection(targetConfigurations, hostConfiguration); }
From source file:com.google.errorprone.bugpatterns.InconsistentHashCode.java
@Override public Description matchClass(ClassTree tree, VisitorState state) { ClassSymbol classSymbol = getSymbol(tree); MethodTree equalsDeclaration = null; MethodTree hashCodeDeclaration = null; for (Tree member : tree.getMembers()) { if (!(member instanceof MethodTree)) { continue; }/*from w w w . j ava2 s. co m*/ MethodTree methodTree = (MethodTree) member; if (hashCodeMethodDeclaration().matches(methodTree, state)) { hashCodeDeclaration = methodTree; } else if (equalsMethodDeclaration().matches(methodTree, state)) { equalsDeclaration = methodTree; } } if (equalsDeclaration == null || hashCodeDeclaration == null) { return Description.NO_MATCH; } // Build up a map of methods to the fields they access for simple methods, i.e. getters. // Not a SetMultimap, because we do want to distinguish between "method was not analyzable" and // "method accessed no fields". Map<MethodSymbol, ImmutableSet<Symbol>> fieldsByMethod = new HashMap<>(); for (Tree member : tree.getMembers()) { if (!(member instanceof MethodTree)) { continue; } MethodTree methodTree = (MethodTree) member; if (!methodTree.equals(equalsDeclaration) && !methodTree.equals(hashCodeDeclaration)) { FieldAccessFinder finder = FieldAccessFinder.scanMethod(state, classSymbol, methodTree); if (!finder.failed()) { fieldsByMethod.put(getSymbol(methodTree), finder.accessedFields()); } } } FieldAccessFinder equalsScanner = FieldAccessFinder.scanMethod(state, classSymbol, equalsDeclaration, fieldsByMethod, HASH_CODE_METHODS); FieldAccessFinder hashCodeScanner = FieldAccessFinder.scanMethod(state, classSymbol, hashCodeDeclaration, fieldsByMethod, EQUALS_METHODS); if (equalsScanner.failed() || hashCodeScanner.failed()) { return Description.NO_MATCH; } ImmutableSet<Symbol> fieldsInHashCode = hashCodeScanner.accessedFields(); ImmutableSet<Symbol> fieldsInEquals = equalsScanner.accessedFields(); Set<Symbol> difference = new HashSet<>(Sets.difference(fieldsInHashCode, fieldsInEquals)); // Special-case the situation where #hashCode uses a field containing `hash` for memoization. difference.removeIf(f -> Ascii.toLowerCase(f.toString()).contains("hash")); String message = String.format(MESSAGE, difference); // Skip cases where equals and hashCode compare the same fields, or equals compares none (and // so is probably checking reference equality). return difference.isEmpty() || fieldsInEquals.isEmpty() ? Description.NO_MATCH : buildDescription(hashCodeDeclaration).setMessage(message).build(); }
From source file:net.caseif.flint.common.arena.CommonArena.java
@Override public Round createRound(ImmutableSet<LifecycleStage> stages) throws IllegalArgumentException, IllegalStateException, OrphanedComponentException { checkState();/*from w w w. ja va2 s.c o m*/ Preconditions.checkState(!getRound().isPresent(), "Cannot create a round in an arena already hosting one"); checkArgument(stages != null && !stages.isEmpty(), "LifecycleStage set must not be null or empty"); ((CommonMinigame) getMinigame()).getRoundMap().put(this, ((IRoundFactory) FactoryRegistry.getFactory(Round.class)).createRound(this, stages)); Preconditions.checkState(getRound().isPresent(), "Cannot get created round from arena! This is a bug."); return getRound().get(); }
From source file:com.facebook.buck.features.project.intellij.IjProjectCommandHelper.java
private ExitCode buildRequiredTargetsWithoutUsingCacheForAnnotatedTargets( TargetGraphAndTargets targetGraphAndTargets, ImmutableSet<BuildTarget> requiredBuildTargets) throws IOException, InterruptedException { ImmutableSet<BuildTarget> annotatedTargets = getTargetsWithAnnotations( targetGraphAndTargets.getTargetGraph(), requiredBuildTargets); ImmutableSet<BuildTarget> unannotatedTargets = Sets.difference(requiredBuildTargets, annotatedTargets) .immutableCopy();/* www . java 2s. c o m*/ ExitCode exitCode = runBuild(unannotatedTargets); if (exitCode != ExitCode.SUCCESS) { addBuildFailureError(); } if (annotatedTargets.isEmpty()) { return exitCode; } ExitCode annotationExitCode = buckBuildRunner.runBuild(annotatedTargets, true); if (exitCode == ExitCode.SUCCESS && annotationExitCode != ExitCode.SUCCESS) { addBuildFailureError(); } return exitCode == ExitCode.SUCCESS ? annotationExitCode : exitCode; }
From source file:com.twitter.common.args.apt.CmdLineProcessor.java
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try {/*ww w . j a va 2s. co m*/ @Nullable Configuration classpathConfiguration = configSupplier.get(); Set<? extends Element> parsers = getAnnotatedElements(roundEnv, ArgParser.class); contributingClassNamesBuilder.addAll(extractClassNames(parsers)); @Nullable Set<String> parsedTypes = getParsedTypes(classpathConfiguration, parsers); Set<? extends Element> cmdlineArgs = getAnnotatedElements(roundEnv, CmdLine.class); contributingClassNamesBuilder.addAll(extractEnclosingClassNames(cmdlineArgs)); Set<? extends Element> positionalArgs = getAnnotatedElements(roundEnv, Positional.class); contributingClassNamesBuilder.addAll(extractEnclosingClassNames(positionalArgs)); ImmutableSet<? extends Element> invalidArgs = Sets.intersection(cmdlineArgs, positionalArgs) .immutableCopy(); if (!invalidArgs.isEmpty()) { error("An Arg cannot be annotated with both @CmdLine and @Positional, found bad Arg " + "fields: %s", invalidArgs); } for (ArgInfo cmdLineInfo : processAnnotatedArgs(parsedTypes, cmdlineArgs, CmdLine.class)) { configBuilder.addCmdLineArg(cmdLineInfo); } for (ArgInfo positionalInfo : processAnnotatedArgs(parsedTypes, positionalArgs, Positional.class)) { configBuilder.addPositionalInfo(positionalInfo); } checkPositionalArgsAreLists(roundEnv); processParsers(parsers); Set<? extends Element> verifiers = getAnnotatedElements(roundEnv, VerifierFor.class); contributingClassNamesBuilder.addAll(extractClassNames(verifiers)); processVerifiers(verifiers); if (roundEnv.processingOver()) { if (classpathConfiguration != null && (!classpathConfiguration.isEmpty() || !configBuilder.isEmpty())) { @Nullable Resource cmdLinePropertiesResource = openCmdLinePropertiesResource(classpathConfiguration); if (cmdLinePropertiesResource != null) { Writer writer = cmdLinePropertiesResource.getWriter(); try { configBuilder.build(classpathConfiguration).store(writer, "Generated via apt by " + getClass().getName()); } finally { closeQuietly(writer); } writeResourceMapping(contributingClassNamesBuilder.build(), cmdLinePropertiesResource.getResource()); } } } // TODO(John Sirois): Investigate narrowing this catch - its not clear there is any need to be // so general. // SUPPRESS CHECKSTYLE RegexpSinglelineJava } catch (RuntimeException e) { // Catch internal errors - when these bubble more useful queued error messages are lost in // some javac implementations. error("Unexpected error completing annotation processing:\n%s", Throwables.getStackTraceAsString(e)); } return true; }
From source file:org.sosy_lab.cpachecker.core.algorithm.pdr.PDRAlgorithm.java
/** Checks for trivial cases and 0-/1-step counterexamples. */ private boolean checkBaseCases(CFANode pStartLocation, ImmutableSet<CFANode> pErrorLocations, ReachedSet pReachedSet, ProverEnvironment pProver) throws CPATransferException, CPAException, InterruptedException, SolverException { // For trivially-safe tasks, no further effort is required if (pErrorLocations.isEmpty()) { return false; }/* w w w. ja v a 2 s .c o m*/ // Check for 0-step counterexample for (CFANode errorLocation : pErrorLocations) { if (pStartLocation.equals(errorLocation)) { logger.log(Level.INFO, "Found errorpath: 0-step counterexample."); return false; } } // Check for 1-step counterexamples for (Block block : backwardTransition.getBlocksTo(pErrorLocations, IS_MAIN_ENTRY)) { pProver.push(block.getFormula()); if (!pProver.isUnsat()) { logger.log(Level.INFO, "Found errorpath: 1-step counterexample.", " \nTransition : \n", block.getFormula()); analyzeCounterexample(Collections.singletonList(block), pReachedSet); return false; } pProver.pop(); } return true; }