List of usage examples for com.google.common.collect ImmutableSet stream
default Stream<E> stream()
From source file:com.facebook.buck.android.toolchain.ndk.impl.AndroidNdkResolver.java
private Optional<Path> findNdkFromRepository(Path repository) { ImmutableSet<Path> repositoryContents; try (DirectoryStream<Path> stream = Files.newDirectoryStream(repository)) { repositoryContents = ImmutableSet.copyOf(stream); } catch (IOException e) { ndkErrorMessage = Optional.of("Unable to read contents of Android ndk.ndk_repository_path or " + "ANDROID_NDK_REPOSITORY at " + repository); return Optional.empty(); }//from ww w . ja va2s. co m VersionStringComparator versionComparator = new VersionStringComparator(); List<Pair<Path, Optional<String>>> availableNdks = repositoryContents.stream().filter(Files::isDirectory) // Pair of path to version number .map(p -> new Pair<>(p, findNdkVersion(p))).filter(pair -> pair.getSecond().isPresent()) .filter(pair -> versionComparator.compare(pair.getSecond().get(), NDK_MIN_UNSUPPORTED_VERSION) < 0) .sorted((o1, o2) -> versionComparator.compare(o2.getSecond().get(), o1.getSecond().get())) .collect(Collectors.toList()); if (availableNdks.isEmpty()) { ndkErrorMessage = Optional.of(repository + " does not contain any valid Android NDK. Make" + " sure to specify ANDROID_NDK_REPOSITORY or ndk.ndk_repository_path."); return Optional.empty(); } if (targetNdkVersion.isPresent()) { if (targetNdkVersion.get().isEmpty()) { ndkErrorMessage = Optional.of(NDK_TARGET_VERSION_IS_EMPTY_MESSAGE); return Optional.empty(); } Optional<Path> targetNdkPath = availableNdks.stream() .filter(p -> versionEquals(targetNdkVersion.get(), p.getSecond().get())).map(Pair::getFirst) .findFirst(); if (targetNdkPath.isPresent()) { return targetNdkPath; } targetNdkPath = availableNdks.stream() .filter(p -> versionStartsWith(targetNdkVersion.get(), p.getSecond().get())).map(Pair::getFirst) .findFirst(); if (targetNdkPath.isPresent()) { return targetNdkPath; } ndkErrorMessage = Optional.of("Target NDK version " + targetNdkVersion.get() + " is not " + "available. The following versions are available: " + availableNdks.stream() .map(Pair::getSecond).map(Optional::get).collect(Collectors.joining(", "))); return Optional.empty(); } LOG.debug("Using Android NDK version %s", availableNdks.get(0).getSecond().get()); return Optional.of(availableNdks.get(0).getFirst()); }
From source file:vazkii.quark.misc.feature.PanoramaMaker.java
@SubscribeEvent public void loadMainMenu(GuiOpenEvent event) { if (overrideMainMenu && !overridenOnce && event.getGui() instanceof GuiMainMenu) { File mcDir = ModuleLoader.configFile.getParentFile().getParentFile(); File panoramasDir = new File(mcDir, "/screenshots/panoramas"); List<File[]> validFiles = new ArrayList(); ImmutableSet<String> set = ImmutableSet.of("panorama_0.png", "panorama_1.png", "panorama_2.png", "panorama_3.png", "panorama_4.png", "panorama_5.png"); if (panoramasDir.exists()) { File[] subDirs;// w w w . j a va 2 s .com File mainMenu = new File(panoramasDir, "main_menu"); if (mainMenu.exists()) subDirs = new File[] { mainMenu }; else subDirs = panoramasDir .listFiles((File f) -> f.isDirectory() && !f.getName().endsWith("fullres")); for (File f : subDirs) if (set.stream().allMatch((String s) -> new File(f, s).exists())) validFiles.add(f.listFiles((File f1) -> set.contains(f1.getName()))); } if (!validFiles.isEmpty()) { File[] files = validFiles.get(new Random().nextInt(validFiles.size())); Arrays.sort(files); Minecraft mc = Minecraft.getMinecraft(); ResourceLocation[] resources = new ResourceLocation[6]; for (int i = 0; i < resources.length; i++) { File f = files[i]; try { BufferedImage img = ImageIO.read(f); DynamicTexture tex = new DynamicTexture(img); String name = "quark:" + f.getName(); resources[i] = mc.getTextureManager().getDynamicTextureLocation(name, tex); } catch (IOException e) { e.printStackTrace(); return; } } try { Field field = ReflectionHelper.findField(GuiMainMenu.class, LibObfuscation.TITLE_PANORAMA_PATHS); field.setAccessible(true); if (Modifier.isFinal(field.getModifiers())) { Field modfield = Field.class.getDeclaredField("modifiers"); modfield.setAccessible(true); modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL); } field.set(null, resources); } catch (Exception e) { e.printStackTrace(); } } overridenOnce = true; } }
From source file:net.lldp.checksims.ChecksimsRunner.java
/** * Main public entrypoint to Checksims. Runs similarity detection according to given configuration. * * @param config Configuration defining how Checksims will be run * @return Map containing output of all output printers requested. Keys are name of output printer. * @throws ChecksimsException Thrown on error performing similarity detection */// w ww .j a v a 2 s . c om public static ImmutableMap<String, String> runChecksims(ChecksimsConfig config) throws ChecksimsException { checkNotNull(config); // Create a logger to log activity Logger logs = LoggerFactory.getLogger(ChecksimsRunner.class); // Set parallelism int threads = config.getNumThreads(); ParallelAlgorithm.setThreadCount(threads); // TODO following line may not be necessary as we no longer use parallel streams? System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "" + threads); ImmutableSet<Submission> submissions = config.getSubmissions(); logs.info("Got " + submissions.size() + " submissions to test."); ImmutableSet<Submission> archiveSubmissions = config.getArchiveSubmissions(); if (!archiveSubmissions.isEmpty()) { logs.info("Got " + archiveSubmissions.size() + " archive submissions to test."); } if (submissions.size() == 0) { throw new ChecksimsException("No student submissions were found - cannot run Checksims!"); } // Apply all preprocessors for (SubmissionPreprocessor p : config.getPreprocessors()) { submissions = ImmutableSet .copyOf(PreprocessSubmissions.process(p, submissions, config.getStatusLogger())); if (!archiveSubmissions.isEmpty()) { archiveSubmissions = ImmutableSet .copyOf(PreprocessSubmissions.process(p, archiveSubmissions, config.getStatusLogger())); } } if (submissions.size() < 2) { throw new ChecksimsException("Did not get at least 2 student submissions! Cannot run Checksims!"); } // Apply algorithm to submissions Set<Pair<Submission, Submission>> allPairs = PairGenerator.generatePairsWithArchive(submissions, archiveSubmissions); Set<AlgorithmResults> results = AlgorithmRunner.runAlgorithm(allPairs, config.getAlgorithm(), config.getStatusLogger()); if (config.isIgnoringInvalid()) { Set<Submission> validSubmissions = new HashSet<>(); Set<Submission> validArchivedSubmissions = new HashSet<>(); Set<AlgorithmResults> validResults = new HashSet<>(); submissions.stream().filter(S -> !S.testFlag("invalid")).forEach(S -> validSubmissions.add(S)); archiveSubmissions.stream().filter(S -> !S.testFlag("invalid")) .forEach(S -> validArchivedSubmissions.add(S)); results.stream().filter(S -> S.isValid()).forEach(S -> validResults.add(S)); submissions = ImmutableSet.copyOf(validSubmissions); archiveSubmissions = ImmutableSet.copyOf(validArchivedSubmissions); results = validResults; } SimilarityMatrix resultsMatrix = SimilarityMatrix.generateMatrix(submissions, archiveSubmissions, results); // All parallel jobs are done, shut down the parallel executor ParallelAlgorithm.shutdownExecutor(); config.getStatusLogger().end(); Map<String, String> outputMap = new HashMap<>(); // Output using all output printers for (MatrixPrinter p : config.getOutputPrinters()) { logs.info("Generating " + p.getName() + " output"); outputMap.put(p.getName(), p.printMatrix(resultsMatrix)); } ChecksimsCommandLine.deleteTempFiles(); return ImmutableMap.copyOf(outputMap); }
From source file:com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig.java
public ArtifactCacheEntries getCacheEntries() { ImmutableSet<DirCacheEntry> dirCacheEntries = getDirCacheEntries(); ImmutableSet<HttpCacheEntry> httpCacheEntries = getHttpCacheEntries(); ImmutableSet<SQLiteCacheEntry> sqliteCacheEntries = getSQLiteCacheEntries(); Predicate<DirCacheEntry> isDirCacheEntryWriteable = dirCache -> dirCache.getCacheReadMode().isWritable(); // Enforce some sanity checks on the config: // - we don't want multiple writeable dir caches pointing to the same directory dirCacheEntries.stream().filter(isDirCacheEntryWriteable) .collect(Collectors.groupingBy(DirCacheEntry::getCacheDir)).forEach((path, dirCachesPerPath) -> { if (dirCachesPerPath.size() > 1) { throw new HumanReadableException( "Multiple writeable dir caches defined for path %s. This is not supported.", path); }/*from w w w .j a va 2s . c o m*/ }); return ArtifactCacheEntries.builder().setDirCacheEntries(dirCacheEntries) .setHttpCacheEntries(httpCacheEntries).setSQLiteCacheEntries(sqliteCacheEntries).build(); }
From source file:com.facebook.buck.features.apple.project.WorkspaceAndProjectGenerator.java
/** * Create individual schemes for each project and associated tests. Provided as a workaround for a * change in Xcode 10 where Apple started building all scheme targets and tests when clicking on a * single item from the test navigator.//from w ww. j a va 2 s . c o m * * @param workspaceName * @param outputDirectory * @param schemeTargets Targets to be considered for scheme. Allows external filtering of targets * included in the project's scheme. * @param generatedProjectToPbxTargets * @param targetToProjectPathMap * @param buildForTestTargets * @param ungroupedTestTargets * @throws IOException */ private void writeWorkspaceSchemesForProjects(String workspaceName, Path outputDirectory, ImmutableSet<PBXTarget> schemeTargets, ImmutableSetMultimap<PBXProject, PBXTarget> generatedProjectToPbxTargets, ImmutableMap<PBXTarget, Path> targetToProjectPathMap, ImmutableSetMultimap<String, PBXTarget> buildForTestTargets, ImmutableSetMultimap<String, PBXTarget> ungroupedTestTargets) throws IOException { for (PBXProject project : generatedProjectToPbxTargets.keys()) { String schemeName = project.getName(); ImmutableSet<PBXTarget> projectTargets = generatedProjectToPbxTargets.get(project); ImmutableSet<PBXTarget> orderedBuildTestTargets = projectTargets.stream() .filter(pbxTarget -> buildForTestTargets.values().contains(pbxTarget)) .collect(ImmutableSet.toImmutableSet()); ImmutableSet<PBXTarget> orderedRunTestTargets = projectTargets.stream() .filter(pbxTarget -> ungroupedTestTargets.values().contains(pbxTarget)) .collect(ImmutableSet.toImmutableSet()); // add all non-test targets as full build targets ImmutableSet<PBXTarget> orderedBuildTargets = projectTargets.stream() .filter(pbxTarget -> schemeTargets.contains(pbxTarget)) .filter(pbxTarget -> !orderedBuildTestTargets.contains(pbxTarget)) .collect(ImmutableSet.toImmutableSet()); SchemeGenerator schemeGenerator = buildSchemeGenerator(targetToProjectPathMap, workspaceName, outputDirectory, schemeName, Optional.empty(), Optional.empty(), orderedBuildTargets, orderedBuildTestTargets, orderedRunTestTargets, Optional.empty(), Optional.empty()); schemeGenerator.writeScheme(); schemeGenerators.put(schemeName, schemeGenerator); } }
From source file:com.facebook.buck.features.go.GoDescriptors.java
static GoCompile createGoCompileRule(BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, ActionGraphBuilder graphBuilder, GoBuckConfig goBuckConfig, Path packageName, ImmutableSet<SourcePath> srcs, List<String> compilerFlags, List<String> assemblerFlags, GoPlatform platform, Iterable<BuildTarget> deps, Iterable<BuildTarget> cgoDeps, List<ListType> goListTypes) { SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); Preconditions.checkState(buildTarget.getFlavors().contains(platform.getFlavor())); ImmutableSet<GoLinkable> linkables = requireGoLinkables(buildTarget, graphBuilder, platform, deps); ImmutableList.Builder<BuildRule> linkableDepsBuilder = ImmutableList.builder(); for (GoLinkable linkable : linkables) { linkableDepsBuilder.addAll(linkable.getDeps(ruleFinder)); }//from ww w . j a v a 2 s. co m BuildTarget target = createSymlinkTreeTarget(buildTarget); SymlinkTree symlinkTree = makeSymlinkTree(target, projectFilesystem, ruleFinder, pathResolver, linkables); graphBuilder.addToIndex(symlinkTree); ImmutableList.Builder<SourcePath> extraAsmOutputsBuilder = ImmutableList.builder(); ImmutableSet.Builder<SourcePath> generatedSrcBuilder = ImmutableSet.builder(); for (BuildTarget cgoBuildTarget : cgoDeps) { CGoLibrary lib = getCGoLibrary(graphBuilder, platform, cgoBuildTarget); generatedSrcBuilder.addAll(lib.getGeneratedGoSource()); extraAsmOutputsBuilder.add(lib.getOutput()); linkableDepsBuilder.add(lib); } LOG.verbose("Symlink tree for compiling %s: %s", buildTarget, symlinkTree.getLinks()); return new GoCompile(buildTarget, projectFilesystem, params.copyAppendingExtraDeps(linkableDepsBuilder.build()) .copyAppendingExtraDeps(ImmutableList.of(symlinkTree)) .copyAppendingExtraDeps(getDependenciesFromSources(ruleFinder, srcs)), symlinkTree, packageName, getPackageImportMap(goBuckConfig.getVendorPaths(), buildTarget.getBasePath(), linkables.stream().flatMap(input -> input.getGoLinkInput().keySet().stream()) .collect(ImmutableList.toImmutableList())), srcs, generatedSrcBuilder.build(), ImmutableList.copyOf(compilerFlags), ImmutableList.copyOf(assemblerFlags), platform, goBuckConfig.getGensymabis(), extraAsmOutputsBuilder.build(), goListTypes); }
From source file:com.facebook.buck.ide.intellij.aggregation.AggregationTree.java
private void aggregateModules(AggregationTreeNode parentNode) { if (parentNode.getChildren().isEmpty()) { return;//from w ww. j a v a2 s .c o m } AggregationModule nodeModule = parentNode.getModule(); if (nodeModule != null && !nodeModule.getModuleType().canBeAggregated()) { return; } Path moduleBasePath = parentNode.getModuleBasePath(); LOG.info("Aggregating module at %s: %s", moduleBasePath, nodeModule); String aggregationTag; IjModuleType rootModuleType; if (nodeModule == null) { aggregationTag = findBestAggregationTag(parentNode); rootModuleType = null; } else { aggregationTag = nodeModule.getAggregationTag(); rootModuleType = nodeModule.getModuleType(); } ImmutableSet<Path> modulePathsToAggregate; if (aggregationTag == null) { modulePathsToAggregate = parentNode.getChildrenPathsByModuleType(IjModuleType.UNKNOWN_MODULE); if (modulePathsToAggregate.isEmpty()) { return; } rootModuleType = IjModuleType.UNKNOWN_MODULE; } else { modulePathsToAggregate = parentNode.getChildrenPathsByModuleTypeOrTag(IjModuleType.UNKNOWN_MODULE, aggregationTag); if (rootModuleType == null) { rootModuleType = parentNode.getChild(modulePathsToAggregate.iterator().next()).getModule() .getModuleType(); } } ImmutableSet<Path> excludes = findExcludes(parentNode, modulePathsToAggregate); List<AggregationModule> modulesToAggregate = modulePathsToAggregate.stream().map(parentNode::getChild) .map(AggregationTreeNode::getModule).collect(Collectors.toList()); modulePathsToAggregate.forEach(parentNode::removeChild); if (nodeModule == null) { parentNode.setModule(ModuleAggregator.aggregate(moduleBasePath, rootModuleType, aggregationTag == null ? modulesToAggregate.iterator().next().getAggregationTag() : aggregationTag, modulesToAggregate, excludes)); } else { parentNode.setModule(ModuleAggregator.aggregate(nodeModule, modulesToAggregate, excludes)); } LOG.info("Module after aggregation: %s", parentNode.getModule()); }
From source file:org.locationtech.geogig.remotes.LsRemoteOp.java
/** * Lists all refs for the given remote./*from ww w .ja va 2s . co m*/ * * @return an immutable set of the refs for the given remote */ @Override protected ImmutableSet<Ref> _call() { final Remote remoteConfig = this.remote.get().orNull(); Preconditions.checkState(remoteRepo != null || remoteConfig != null, "Remote was not provided"); if (local) { checkArgument(remoteConfig != null, "if retrieving local remote refs, a Remote must be provided"); return locallyKnownRefs(remoteConfig); } ImmutableSet<Ref> remoteRefs; IRemoteRepo remoteRepo = this.remoteRepo; final boolean closeRemote = remoteRepo == null; if (remoteRepo == null) { remoteRepo = openRemote(remoteConfig); getProgressListener() .setDescription("Connected to remote " + remoteConfig.getName() + ". Retrieving references"); } Optional<Ref> headRef = Optional.absent(); try { remoteRefs = remoteRepo.listRefs(repository(), getBranches, getTags); if (getHead) { headRef = remoteRepo.headRef(); } } finally { if (closeRemote) { remoteRepo.close(); } } if (headRef.isPresent()) { Set<Ref> refs = Sets.newHashSet(remoteRefs); refs.add(headRef.get()); remoteRefs = ImmutableSet.copyOf(refs); } Set<Ref> filtered = remoteRefs.stream().filter(r -> remoteConfig.mapToLocal(r.getName()).isPresent()) .collect(Collectors.toSet()); return ImmutableSet.copyOf(filtered); }
From source file:com.google.errorprone.bugpatterns.AbstractArgumentParameterChecker.java
private Description findReplacements(List<? extends ExpressionTree> args, com.sun.tools.javac.util.List<VarSymbol> params, boolean isVarArgs, VisitorState state, Tree tree) { if (args.isEmpty()) { return Description.NO_MATCH; }//from w ww.ja va 2 s .c om ImmutableSet<PotentialReplacement> potentialReplacements = potentialReplacementsFunction .apply(state.withPath(new TreePath(state.getPath(), args.get(0)))); SuggestedFix.Builder fix = SuggestedFix.builder(); // Don't suggest for the varargs parameter. // TODO(eaftan): Reconsider this, especially if the argument is of array type or is itself // a varargs parameter. int maxArg = isVarArgs ? params.size() - 1 : params.size(); for (int i = 0; i < maxArg; i++) { ExpressionTree arg = args.get(i); VarSymbol param = params.get(i); if (!validKinds.contains(arg.getKind()) || !parameterPredicate.test(param)) { continue; } String extractedArgumentName = extractArgumentName(arg); if (extractedArgumentName == null) { continue; } double currSimilarity = similarityMetric.applyAsDouble(extractedArgumentName, param.getSimpleName().toString()); if (1.0 - currSimilarity < beta) { // No way for any replacement to be at least BETA better than the current argument continue; } ReplacementWithSimilarity bestReplacement = potentialReplacements.stream() .filter(replacement -> !replacement.sym().equals(ASTHelpers.getSymbol(arg))) .filter(replacement -> isSubtypeHandleCompletionFailures(replacement.sym(), param, state)) .map(replacement -> ReplacementWithSimilarity.create(replacement, similarityMetric.applyAsDouble(replacement.argumentName(), param.getSimpleName().toString()))) .max(Comparator.comparingDouble(ReplacementWithSimilarity::similarity)).orElse(null); if ((bestReplacement != null) && (bestReplacement.similarity() - currSimilarity >= beta)) { fix.replace(arg, bestReplacement.replacement().replacementString()); } } if (fix.isEmpty()) { return Description.NO_MATCH; } else { return describeMatch(tree, fix.build()); } }
From source file:com.facebook.buck.rules.keys.DefaultDependencyFileRuleKeyFactory.java
@Override public Pair<RuleKey, ImmutableSet<SourcePath>> buildManifestKey(SupportsDependencyFileRuleKey rule) throws IOException { Builder builder = newInstance(rule); builder.setReflectively("buck.key_type", "manifest"); ImmutableSet<SourcePath> inputs = ImmutableSet.copyOf(builder.getIterableInputsSoFar()); Optional<ImmutableSet<SourcePath>> possibleDepFileSourcePaths = rule.getPossibleInputSourcePaths(); final ImmutableSet<SourcePath> depFileInputs; if (possibleDepFileSourcePaths.isPresent()) { // possibleDepFileSourcePaths is an ImmutableSortedSet which implements contains() via // binary search rather than via hashing. Thus taking the intersection/difference // is O(n*log(n)). Here, we make a hash-based copy of the set, so that intersection // will be reduced to O(N). ImmutableSet<SourcePath> possibleDepFileSourcePathsUnsorted = ImmutableSet .copyOf(possibleDepFileSourcePaths.get()); Sets.SetView<SourcePath> nonDepFileInputs = Sets.difference(inputs, possibleDepFileSourcePathsUnsorted); for (SourcePath input : nonDepFileInputs) { builder.setSourcePathDirectly(input); }//from w ww . j a va 2s .com depFileInputs = ImmutableSet.copyOf(Sets.intersection(inputs, possibleDepFileSourcePathsUnsorted)); } else { // If not present, we treat all the input files as covered by dep file. depFileInputs = inputs; } // If an input path representing a metadata file that might be read by an annotation processor // has changed, we cannot use the dep-file based rule key, so we ensure the list of metadata // files are added to the builder directly. ImmutableSortedSet<String> metadataSourcePaths = depFileInputs.stream() .filter(path -> path instanceof ArchiveMemberSourcePath) .filter(path -> ((ArchiveMemberSourcePath) path).getMemberPath().startsWith(METADATA_DIR)) .map(SourcePath::toString).collect(MoreCollectors.toImmutableSortedSet()); builder.setReflectively("buck.dep_file_metadata_list", metadataSourcePaths); return new Pair<>(builder.build(), depFileInputs); }