List of usage examples for com.google.common.collect ImmutableSet contains
boolean contains(Object o);
From source file:com.facebook.buck.rules.CellProvider.java
/** * Create a cell provider at a given root. *///from w w w. ja v a 2s. c om public static CellProvider createForLocalBuild(ProjectFilesystem rootFilesystem, Watchman watchman, BuckConfig rootConfig, CellConfig rootCellConfigOverrides, KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) throws IOException { DefaultCellPathResolver rootCellCellPathResolver = DefaultCellPathResolver .createWithConfigRepositoriesSection(rootFilesystem.getRootPath(), rootConfig.getEntriesForSection(DefaultCellPathResolver.REPOSITORIES_SECTION)); ImmutableMap<RelativeCellName, Path> transitiveCellPathMapping = rootCellCellPathResolver .getTransitivePathMapping(); ImmutableMap<Path, RawConfig> pathToConfigOverrides; try { pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(transitiveCellPathMapping); } catch (CellConfig.MalformedOverridesException e) { throw new HumanReadableException(e.getMessage()); } ImmutableSet<Path> allRoots = ImmutableSet.copyOf(transitiveCellPathMapping.values()); return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() { @Override public Cell load(Path cellPath) throws IOException, InterruptedException { cellPath = cellPath.toRealPath().normalize(); Preconditions.checkState(allRoots.contains(cellPath), "Cell %s outside of transitive closure of root cell (%s).", cellPath, allRoots); RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(cellPath)) .orElse(RawConfig.of(ImmutableMap.of())); Config config = Configs.createDefaultConfig(cellPath, configOverrides); DefaultCellPathResolver cellPathResolver = new DefaultCellPathResolver(cellPath, config); ProjectFilesystem cellFilesystem = new ProjectFilesystem(cellPath, config); BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(), rootConfig.getPlatform(), rootConfig.getEnvironment(), cellPathResolver); // TODO(13777679): cells in other watchman roots do not work correctly. return new Cell(cellPathResolver.getKnownRoots(), cellFilesystem, watchman, buckConfig, knownBuildRuleTypesFactory, cellProvider); } }, cellProvider -> { try { return new Cell(rootCellCellPathResolver.getKnownRoots(), rootFilesystem, watchman, rootConfig, knownBuildRuleTypesFactory, cellProvider); } catch (InterruptedException e) { throw new RuntimeException("Interrupted while loading root cell", e); } catch (IOException e) { throw new HumanReadableException("Failed to load root cell", e); } }); }
From source file:com.facebook.buck.core.cell.impl.LocalCellProviderFactory.java
/** Create a cell provider at a given root. */ public static CellProvider create(ProjectFilesystem rootFilesystem, BuckConfig rootConfig, CellConfig rootCellConfigOverrides, ImmutableMap<CellName, Path> cellPathMapping, CellPathResolver rootCellCellPathResolver, BuckModuleManager moduleManager, ToolchainProviderFactory toolchainProviderFactory, ProjectFilesystemFactory projectFilesystemFactory, UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) { ImmutableMap<Path, RawConfig> pathToConfigOverrides; try {//from ww w . ja va 2s . co m pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(cellPathMapping); } catch (InvalidCellOverrideException e) { throw new HumanReadableException(e.getMessage()); } ImmutableSet<Path> allRoots = ImmutableSet.copyOf(cellPathMapping.values()); return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() { @Override public Cell load(Path cellPath) throws IOException, InterruptedException { Path normalizedCellPath = cellPath.toRealPath().normalize(); Preconditions.checkState(allRoots.contains(normalizedCellPath), "Cell %s outside of transitive closure of root cell (%s).", normalizedCellPath, allRoots); RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(normalizedCellPath)) .orElse(RawConfig.of(ImmutableMap.of())); Config config = Configs.createDefaultConfig(normalizedCellPath, configOverrides); ImmutableMap<String, Path> cellMapping = DefaultCellPathResolver .getCellPathsFromConfigRepositoriesSection(cellPath, config.get(DefaultCellPathResolver.REPOSITORIES_SECTION)); // The cell should only contain a subset of cell mappings of the root cell. cellMapping.forEach((name, path) -> { Path pathInRootResolver = rootCellCellPathResolver.getCellPaths().get(name); if (pathInRootResolver == null) { throw new HumanReadableException( "In the config of %s: %s.%s must exist in the root cell's cell mappings.", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name); } else if (!pathInRootResolver.equals(path)) { throw new HumanReadableException( "In the config of %s: %s.%s must point to the same directory as the root " + "cell's cell mapping: (root) %s != (current) %s", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name, pathInRootResolver, path); } }); CellPathResolver cellPathResolver = new CellPathResolverView(rootCellCellPathResolver, cellMapping.keySet(), cellPath); Optional<EmbeddedCellBuckOutInfo> embeddedCellBuckOutInfo = Optional.empty(); Optional<String> canonicalCellName = cellPathResolver.getCanonicalCellName(normalizedCellPath); if (rootConfig.getView(BuildBuckConfig.class).isEmbeddedCellBuckOutEnabled() && canonicalCellName.isPresent()) { embeddedCellBuckOutInfo = Optional .of(EmbeddedCellBuckOutInfo.of(rootFilesystem.resolve(rootFilesystem.getRootPath()), rootFilesystem.getBuckPaths(), canonicalCellName.get())); } ProjectFilesystem cellFilesystem = projectFilesystemFactory .createProjectFilesystem(normalizedCellPath, config, embeddedCellBuckOutInfo); BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(), rootConfig.getPlatform(), rootConfig.getEnvironment(), buildTargetName -> unconfiguredBuildTargetFactory.create(cellPathResolver, buildTargetName)); RuleKeyConfiguration ruleKeyConfiguration = ConfigRuleKeyConfigurationFactory.create(buckConfig, moduleManager); ToolchainProvider toolchainProvider = toolchainProviderFactory.create(buckConfig, cellFilesystem, ruleKeyConfiguration); // TODO(13777679): cells in other watchman roots do not work correctly. return ImmutableCell.of(cellPathResolver.getKnownRoots(), canonicalCellName, cellFilesystem, buckConfig, cellProvider, toolchainProvider, ruleKeyConfiguration, cellPathResolver); } }, cellProvider -> RootCellFactory.create(cellProvider, rootCellCellPathResolver, toolchainProviderFactory, rootFilesystem, moduleManager, rootConfig)); }
From source file:com.google.caliper.runner.instrument.InstrumentModule.java
@RunScoped @Provides/*w ww . java 2 s .co m*/ static ImmutableSet<Instrument> provideInstruments(CaliperOptions options, final CaliperConfig config, Map<Class<? extends Instrument>, Provider<Instrument>> availableInstruments, ImmutableSet<VmType> vmTypes, @Stderr PrintWriter stderr) throws InvalidCommandException { ImmutableSet.Builder<Instrument> builder = ImmutableSet.builder(); ImmutableSet<String> configuredInstruments = config.getConfiguredInstruments(); ImmutableSet<String> selectedInstruments = options.instrumentNames(); if (selectedInstruments.isEmpty()) { selectedInstruments = config.getDefaultInstruments(); } for (final String instrumentName : selectedInstruments) { if (!configuredInstruments.contains(instrumentName)) { throw new InvalidCommandException( "%s is not a configured instrument (%s). " + "use --print-config to see the configured instruments.", instrumentName, configuredInstruments); } final InstrumentConfig instrumentConfig = config.getInstrumentConfig(instrumentName); String className = instrumentConfig.className(); try { Class<? extends Instrument> clazz = Util.lenientClassForName(className) .asSubclass(Instrument.class); Provider<Instrument> instrumentProvider = availableInstruments.get(clazz); if (instrumentProvider == null) { throw new InvalidInstrumentException("Instrument %s not supported", className); } if (isSupportedByAllVms(clazz, vmTypes)) { Instrument instrument = instrumentProvider.get(); InstrumentInjectorModule injectorModule = new InstrumentInjectorModule(instrumentConfig, instrumentName); InstrumentComponent instrumentComponent = DaggerInstrumentComponent.builder() .instrumentInjectorModule(injectorModule).build(); instrumentComponent.injectInstrument(instrument); builder.add(instrument); } else { stderr.format("Instrument %s not supported on at least one target VM; ignoring\n", className); } } catch (ClassNotFoundException e) { throw new InvalidCommandException("Cannot find instrument class '%s'", className); } } return builder.build(); }
From source file:com.spectralogic.dsbrowser.gui.services.ds3Panel.Ds3PanelService.java
public static Optional<ImmutableList<Bucket>> setSearchableBucket( final ObservableList<TreeItem<Ds3TreeTableValue>> selectedItem, final Session session, final TreeTableView<Ds3TreeTableValue> treeTableView) { try {/*from www . ja v a2 s . c o m*/ if (null != treeTableView) { ObservableList<TreeItem<Ds3TreeTableValue>> selectedItemTemp = selectedItem; if (null == selectedItemTemp) { selectedItemTemp = FXCollections.observableArrayList(); if (null != treeTableView.getRoot() && null != treeTableView.getRoot().getValue()) { selectedItemTemp.add(treeTableView.getRoot()); } } final GetBucketsSpectraS3Request getBucketsSpectraS3Request = new GetBucketsSpectraS3Request(); final GetBucketsSpectraS3Response response = session.getClient() .getBucketsSpectraS3(getBucketsSpectraS3Request); final ImmutableList<Bucket> buckets = response.getBucketListResult().getBuckets().stream() .collect(GuavaCollectors.immutableList()); if (!Guard.isNullOrEmpty(selectedItemTemp)) { final ImmutableSet<String> bucketNameSet = selectedItemTemp.stream() .map(item -> item.getValue().getBucketName()).collect(GuavaCollectors.immutableSet()); return Optional .ofNullable(buckets.stream().filter(bucket -> bucketNameSet.contains(bucket.getName())) .collect(GuavaCollectors.immutableList())); } else { return Optional.ofNullable(buckets); } } else { throw new NullPointerException("TreeTableView can't be null"); } } catch (final Exception e) { LOG.error("Something went wrong!", e); return Optional.empty(); } }
From source file:com.facebook.buck.util.zip.Zip.java
/** Walks the file tree rooted in baseDirectory to create zip entries */ public static void walkBaseDirectoryToCreateEntries(ProjectFilesystem filesystem, Map<String, Pair<CustomZipEntry, Optional<Path>>> entries, Path baseDir, ImmutableSet<Path> paths, boolean junkPaths, ZipCompressionLevel compressionLevel) throws IOException { // Since filesystem traversals can be non-deterministic, sort the entries we find into // a tree map before writing them out. FileVisitor<Path> pathFileVisitor = new SimpleFileVisitor<Path>() { private boolean isSkipFile(Path file) { return !paths.isEmpty() && !paths.contains(file); }//from w w w . j a v a 2s .c o m private String getEntryName(Path path) { Path relativePath = junkPaths ? path.getFileName() : baseDir.relativize(path); return MorePaths.pathWithUnixSeparators(relativePath); } private CustomZipEntry getZipEntry(String entryName, Path path, BasicFileAttributes attr) throws IOException { boolean isDirectory = filesystem.isDirectory(path); if (isDirectory) { entryName += "/"; } CustomZipEntry entry = new CustomZipEntry(entryName); // We want deterministic ZIPs, so avoid mtimes. entry.setFakeTime(); entry.setCompressionLevel( isDirectory ? ZipCompressionLevel.NONE.getValue() : compressionLevel.getValue()); // If we're using STORED files, we must manually set the CRC, size, and compressed size. if (entry.getMethod() == ZipEntry.STORED && !isDirectory) { entry.setSize(attr.size()); entry.setCompressedSize(attr.size()); entry.setCrc(new ByteSource() { @Override public InputStream openStream() throws IOException { return filesystem.newFileInputStream(path); } }.hash(Hashing.crc32()).padToLong()); } long externalAttributes = filesystem.getFileAttributesForZipEntry(path); LOG.verbose("Setting mode for entry %s path %s to 0x%08X", entryName, path, externalAttributes); entry.setExternalAttributes(externalAttributes); return entry; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!isSkipFile(file)) { CustomZipEntry entry = getZipEntry(getEntryName(file), file, attrs); entries.put(entry.getName(), new Pair<>(entry, Optional.of(file))); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (!dir.equals(baseDir) && !isSkipFile(dir)) { CustomZipEntry entry = getZipEntry(getEntryName(dir), dir, attrs); entries.put(entry.getName(), new Pair<>(entry, Optional.empty())); } return FileVisitResult.CONTINUE; } }; filesystem.walkRelativeFileTree(baseDir, pathFileVisitor); }
From source file:com.google.devtools.build.lib.skyframe.FilesystemValueChecker.java
private static boolean shouldCheckFile(ImmutableSet<PathFragment> knownModifiedOutputFiles, Artifact artifact) { return knownModifiedOutputFiles == null || knownModifiedOutputFiles.contains(artifact.getExecPath()); }
From source file:com.facebook.buck.rust.RustCompileUtils.java
/** * Given a list of sources, return the one which is the root based on the defaults and user * parameters.//from w ww.j a v a 2 s. c o m * * @param resolver Source path resolver for rule * @param crate Name of crate * @param defaults Default names for this rule (library, binary, etc) * @param sources List of sources * @return The matching source */ public static Optional<SourcePath> getCrateRoot(SourcePathResolver resolver, String crate, Optional<SourcePath> crateRoot, ImmutableSet<String> defaults, Stream<SourcePath> sources) { String crateName = String.format("%s.rs", crate); ImmutableList<SourcePath> res = sources.filter(src -> { String name = resolver.getRelativePath(src).getFileName().toString(); return crateRoot.map(src::equals).orElse(false) || defaults.contains(name) || name.equals(crateName); }).collect(MoreCollectors.toImmutableList()); if (res.size() == 1) { return Optional.of(res.get(0)); } else { return Optional.empty(); } }
From source file:ru.rulex.conclusion.IteratorsFacade.java
/** * @param immutableAssertionUnit//from w w w . j a v a2 s.c o m * @param source * @param excepts * @param <T> * @return Iterator<T> */ public static <T> Iterator<T> whereIterator(final ImmutableAssertionUnit<T> immutableAssertionUnit, final ImmutableList<T> source, final ImmutableSet<T> excepts) { return new AbstractIterator<T>() { private final UnmodifiableIterator<T> iterator = source.iterator(); private final ConclusionStatePathTrace pathTrace = ConclusionStatePathTrace.defaultInstance(); private IterationState state = IterationState.Regular; @Override public boolean hasNext() { switch (state) { case Regular: while (iterator.hasNext()) { T event = iterator.next(); if (!excepts.contains(event) && immutableAssertionUnit.isSatisfies(pathTrace, event)) { state = IterationState.Exit; return computeNext(event); } } case Exit: { return interrupt; } } return interrupt; } }; }
From source file:com.google.polymer.JsRenamer.java
/** * Outputs the source equivalent of the abstract syntax tree. * @param node The JavaScript abstract syntax tree. * @param outputFormat The source output format options. * @return The equivalent JavaScript source. *///from w w w. ja v a 2 s . c om private static String toSource(Node node, ImmutableSet<OutputFormat> outputFormat) { CompilerOptions options = new CompilerOptions(); options.setPrettyPrint(outputFormat.contains(OutputFormat.PRETTY)); options.setPreferSingleQuotes(outputFormat.contains(OutputFormat.SINGLE_QUOTE_STRINGS)); // The Closure Compiler treats the 'use strict' directive as a property of a node. CodeBuilder // doesn't consider directives during its code generation. Instead, it inserts the 'use strict' // directive if it is in a strict language mode. Set<String> directives = node.getDirectives(); if ((directives != null) && directives.contains("use strict")) { options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT6_STRICT); } options.skipAllCompilerPasses(); Compiler compiler = new Compiler(); compiler.disableThreads(); compiler.initOptions(options); Compiler.CodeBuilder cb = new Compiler.CodeBuilder(); compiler.toSource(cb, 0, node); return cb.toString(); }
From source file:com.facebook.buck.io.watchman.WatchmanFactory.java
/** * Queries for the watchman clock-id Executes the underlying watchman query: {@code watchman clock * (sync_timeout: 100)}/*from ww w . ja va 2 s . c o m*/ * * @param watchmanClient to use for the query * @param watchRoot path to the root of the watch-project * @param clock used to compute timeouts and statistics * @param timeoutNanos for the watchman query * @return If successful, a {@link String} containing the watchman clock id */ private static Optional<String> queryClock(WatchmanClient watchmanClient, String watchRoot, ImmutableSet<Capability> capabilities, Clock clock, long timeoutNanos) throws IOException, InterruptedException { Optional<String> clockId = Optional.empty(); long clockStartTimeNanos = clock.nanoTime(); ImmutableMap<String, Object> args = capabilities.contains(Capability.CLOCK_SYNC_TIMEOUT) ? ImmutableMap.of("sync_timeout", WATCHMAN_CLOCK_SYNC_TIMEOUT) : ImmutableMap.of(); Optional<? extends Map<String, ?>> result = watchmanClient.queryWithTimeout(timeoutNanos, "clock", watchRoot, args); if (result.isPresent()) { Map<String, ?> clockResult = result.get(); clockId = Optional.ofNullable((String) clockResult.get("clock")); } if (clockId.isPresent()) { Map<String, ?> map = result.get(); clockId = Optional.ofNullable((String) map.get("clock")); LOG.info("Took %d ms to query for initial clock id %s", TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - clockStartTimeNanos), clockId); } else { LOG.warn("Took %d ms but could not get an initial clock id. Falling back to a named cursor", TimeUnit.NANOSECONDS.toMillis(clock.nanoTime() - clockStartTimeNanos)); } return clockId; }