List of usage examples for com.google.common.collect ImmutableMap.Builder putAll
public final void putAll(Map<? extends K, ? extends V> map)
From source file:com.facebook.buck.apple.xcode.ProjectGenerator.java
/** * Create project level (if it does not exist) and target level configuration entries. * * Each configuration should have an empty entry at the project level. The target level entries * combine the configuration values of every layer into a single configuration file that is * effectively laid out in layers./*from www . j a v a 2 s. c o m*/ */ private void setTargetBuildConfigurations(BuildTarget buildTarget, PBXTarget target, PBXGroup targetGroup, ImmutableSet<XcodeRuleConfiguration> configurations, ImmutableMap<String, String> extraBuildSettings) throws IOException { ImmutableMap.Builder<String, String> extraConfigsBuilder = ImmutableMap.builder(); extraConfigsBuilder.putAll(extraBuildSettings).put("TARGET_NAME", getProductName(buildTarget)) .put("SRCROOT", relativizeBuckRelativePathToGeneratedProject(buildTarget, "").toString()); // HACK: GCC_PREFIX_HEADER needs to be modified because the path is referenced relative to // project root, so if the project is generated in a different place from the BUCK file, it // would break. This forces it to be based off of SRCROOT, which is overriden to point to the // BUCK file location. // However, when using REFERENCE_EXISTING_XCCONFIGS, this setting is not put into another layer, // and therefore may override an existing setting in the target-inline-config level. // Fortunately, this option is only set when we are generating separated projects, which are // placed next to the BUCK files, so avoiding this is OK. // In the long run, setting should be written relative to SRCROOT everywhere, and this entire // hack can be deleted. if (!options.contains(Option.REFERENCE_EXISTING_XCCONFIGS)) { extraConfigsBuilder.put("GCC_PREFIX_HEADER", "$(SRCROOT)/$(inherited)"); } ImmutableMap<String, String> extraConfigs = extraConfigsBuilder.build(); PBXGroup configurationsGroup = targetGroup.getOrCreateChildGroupByName("Configurations"); for (XcodeRuleConfiguration configuration : configurations) { if (options.contains(Option.REFERENCE_EXISTING_XCCONFIGS)) { ConfigInXcodeLayout layers = extractXcodeConfigurationLayers(buildTarget, configuration); xcodeConfigurationLayersMultimapBuilder.put(configuration.getName(), layers); XCBuildConfiguration outputConfiguration = target.getBuildConfigurationList() .getBuildConfigurationsByName().getUnchecked(configuration.getName()); if (layers.targetLevelConfigFile.isPresent()) { PBXFileReference fileReference = configurationsGroup.getOrCreateFileReferenceBySourceTreePath( new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT, this.repoRootRelativeToOutputDirectory .resolve(layers.targetLevelConfigFile.get()).normalize())); outputConfiguration.setBaseConfigurationReference(fileReference); NSDictionary inlineSettings = new NSDictionary(); Iterable<Map.Entry<String, String>> entries = Iterables .concat(layers.targetLevelInlineSettings.entrySet(), extraConfigs.entrySet()); for (Map.Entry<String, String> entry : entries) { inlineSettings.put(entry.getKey(), entry.getValue()); } outputConfiguration.setBuildSettings(inlineSettings); } } else { Path outputConfigurationDirectory = outputDirectory.resolve("Configurations"); projectFilesystem.mkdirs(outputConfigurationDirectory); Path originalProjectPath = projectFilesystem .getPathForRelativePath(Paths.get(buildTarget.getBasePathWithSlash())); // XCConfig search path is relative to the xcode project and the file itself. ImmutableList<Path> searchPaths = ImmutableList.of(originalProjectPath); // Call for effect to create a stub configuration entry at project level. project.getBuildConfigurationList().getBuildConfigurationsByName() .getUnchecked(configuration.getName()); // Write an xcconfig that embodies all the config levels, and set that as the target config. Path configurationFilePath = outputConfigurationDirectory .resolve(mangledBuildTargetName(buildTarget) + "-" + configuration.getName() + ".xcconfig"); String serializedConfiguration = serializeBuildConfiguration(configuration, searchPaths, extraConfigs); projectFilesystem.writeContentsToPath(serializedConfiguration, configurationFilePath); PBXFileReference fileReference = configurationsGroup.getOrCreateFileReferenceBySourceTreePath( new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT, this.repoRootRelativeToOutputDirectory.resolve(configurationFilePath))); XCBuildConfiguration outputConfiguration = target.getBuildConfigurationList() .getBuildConfigurationsByName().getUnchecked(configuration.getName()); outputConfiguration.setBaseConfigurationReference(fileReference); } } }
From source file:com.google.firebase.messaging.WebpushNotification.java
private WebpushNotification(Builder builder) { ImmutableMap.Builder<String, Object> fields = ImmutableMap.builder(); if (!builder.actions.isEmpty()) { fields.put("actions", ImmutableList.copyOf(builder.actions)); }/*from w w w . j a va 2 s.co m*/ addNonNullNonEmpty(fields, "badge", builder.badge); addNonNullNonEmpty(fields, "body", builder.body); addNonNull(fields, "data", builder.data); addNonNullNonEmpty(fields, "dir", builder.direction != null ? builder.direction.value : null); addNonNullNonEmpty(fields, "icon", builder.icon); addNonNullNonEmpty(fields, "image", builder.image); addNonNullNonEmpty(fields, "lang", builder.language); addNonNull(fields, "renotify", builder.renotify); addNonNull(fields, "requireInteraction", builder.requireInteraction); addNonNull(fields, "silent", builder.silent); addNonNullNonEmpty(fields, "tag", builder.tag); addNonNull(fields, "timestamp", builder.timestampMillis); addNonNullNonEmpty(fields, "title", builder.title); addNonNull(fields, "vibrate", builder.vibrate); fields.putAll(builder.customData); this.fields = fields.build(); }
From source file:com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService.java
private Map<String, SctId> readSctIds(final Set<String> componentIds) { HttpPost bulkRequest = null;//from ww w .java 2 s. co m HttpGet singleRequest = null; try { if (componentIds.size() > 1) { LOGGER.debug("Sending bulk component ID get request."); final ImmutableMap.Builder<String, SctId> resultBuilder = ImmutableMap.builder(); for (final Collection<String> ids : Iterables.partition(componentIds, BULK_LIMIT)) { final String idsAsString = Joiner.on(',').join(ids); final ObjectNode idsAsJson = mapper.createObjectNode().put("sctids", idsAsString); bulkRequest = client.httpPost(String.format("sct/bulk/ids/?token=%s", getToken()), idsAsJson); final String response = execute(bulkRequest); final SctId[] sctIds = mapper.readValue(response, SctId[].class); final Map<String, SctId> sctIdMap = Maps.uniqueIndex(Arrays.asList(sctIds), SctId::getSctid); resultBuilder.putAll(sctIdMap); } return resultBuilder.build(); } else { final String componentId = Iterables.getOnlyElement(componentIds); LOGGER.debug(String.format("Sending component ID %s get request.", componentId)); singleRequest = httpGet(String.format("sct/ids/%s?token=%s", componentId, getToken())); final String response = execute(singleRequest); final SctId sctId = mapper.readValue(response, SctId.class); return ImmutableMap.of(sctId.getSctid(), sctId); } } catch (IOException e) { throw new SnowowlRuntimeException("Exception while getting all IDs", e); } finally { release(bulkRequest); release(singleRequest); } }
From source file:com.facebook.buck.features.apple.project.WorkspaceAndProjectGenerator.java
private void processGenerationResult( ImmutableSetMultimap.Builder<PBXProject, PBXTarget> generatedProjectToPbxTargetsBuilder, ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder, ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder, GenerationResult result) { requiredBuildTargetsBuilder.addAll(result.getRequiredBuildTargets()); ImmutableSortedSet<Path> relativeXcconfigPaths = result.getXcconfigPaths().stream() .map((Path p) -> rootCell.getFilesystem().relativize(p)) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())); xcconfigPathsBuilder.addAll(relativeXcconfigPaths); filesToCopyInXcodeBuilder.addAll(result.getFilesToCopyInXcode()); buildTargetToPbxTargetMapBuilder.putAll(result.getBuildTargetToGeneratedTargetMap()); generatedProjectToPbxTargetsBuilder.putAll(result.getGeneratedProjectToPbxTargets()); for (PBXTarget target : result.getBuildTargetToGeneratedTargetMap().values()) { targetToProjectPathMapBuilder.put(target, result.getProjectPath()); }// www . jav a 2s.c om }
From source file:org.apache.druid.query.lookup.LookupReferencesManager.java
private void startLookups(final List<LookupBean> lookupBeanList) { final ImmutableMap.Builder<String, LookupExtractorFactoryContainer> builder = ImmutableMap.builder(); final ExecutorService executorService = Execs.multiThreaded(lookupConfig.getNumLookupLoadingThreads(), "LookupReferencesManager-Startup-%s"); final CompletionService<Map.Entry<String, LookupExtractorFactoryContainer>> completionService = new ExecutorCompletionService<>( executorService);/*from www.j av a 2s. c o m*/ final List<LookupBean> remainingLookups = new ArrayList<>(lookupBeanList); try { LOG.info("Starting lookup loading process"); for (int i = 0; i < lookupConfig.getLookupStartRetries() && !remainingLookups.isEmpty(); i++) { LOG.info("Round of attempts #%d, [%d] lookups", i + 1, remainingLookups.size()); final Map<String, LookupExtractorFactoryContainer> successfulLookups = startLookups( remainingLookups, completionService); builder.putAll(successfulLookups); remainingLookups.removeIf(l -> successfulLookups.containsKey(l.getName())); } if (!remainingLookups.isEmpty()) { LOG.warn("Failed to start the following lookups after [%d] attempts: [%s]", lookupConfig.getLookupStartRetries(), remainingLookups); } stateRef.set(new LookupUpdateState(builder.build(), ImmutableList.of(), ImmutableList.of())); } catch (InterruptedException | RuntimeException e) { LOG.error(e, "Failed to finish lookup load process."); } finally { executorService.shutdownNow(); } }
From source file:com.facebook.buck.parser.PythonDslProjectBuildFileParser.java
/** Initialize the parser, starting buck.py. */ private void init() throws IOException { try (SimplePerfEvent.Scope scope = SimplePerfEvent.scope(buckEventBus, PerfEventId.of("ParserInit"))) { ImmutableMap.Builder<String, String> pythonEnvironmentBuilder = ImmutableMap .builderWithExpectedSize(environment.size()); // Strip out PYTHONPATH. buck.py manually sets this to include only nailgun. We don't want // to inject nailgun into the parser's PYTHONPATH, so strip that value out. // If we wanted to pass on some environmental PYTHONPATH, we would have to do some actual // merging of this and the BuckConfig's python module search path. // Also ignore PYTHONHASHSEED environment variable passed by clients since Buck manages it to // prevent non-determinism. pythonEnvironmentBuilder.putAll(Maps.filterKeys(environment, k -> !PYTHONPATH_ENV_VAR_NAME.equals(k) && !PYTHON_HASH_SEED_ENV_VAR_NAME.equals(k))); // set Python hash seed to a fixed number to make parsing reproducible pythonEnvironmentBuilder.put(PYTHON_HASH_SEED_ENV_VAR_NAME, PYTHON_HASH_SEED_VALUE); if (options.getPythonModuleSearchPath().isPresent()) { pythonEnvironmentBuilder.put(PYTHONPATH_ENV_VAR_NAME, options.getPythonModuleSearchPath().get()); }//from w w w.j a v a 2 s. c o m ImmutableMap<String, String> pythonEnvironment = pythonEnvironmentBuilder.build(); ProcessExecutorParams params = ProcessExecutorParams.builder().setCommand(buildArgs()) .setEnvironment(pythonEnvironment).build(); LOG.debug("Starting buck.py command: %s environment: %s", params.getCommand(), params.getEnvironment()); buckPyProcess = processExecutor.launchProcess(params); LOG.debug("Started process %s successfully", buckPyProcess); buckPyProcessInput = createParserInputStream(Objects.requireNonNull(buckPyProcess).getInputStream(), processedBytes.isPresent()); buckPyProcessJsonGenerator = ObjectMappers.createGenerator(buckPyProcess.getOutputStream()); // We have to wait to create the JsonParser until after we write our // first request, because Jackson "helpfully" synchronously reads // from the InputStream trying to detect whether the encoding is // UTF-8 or UTF-16 as soon as you create a JsonParser: // // https://git.io/vSgnA // // Since buck.py doesn't write any data until after it receives // a query, creating the JsonParser here would hang indefinitely. InputStream stderr = buckPyProcess.getErrorStream(); AtomicInteger numberOfLines = new AtomicInteger(0); AtomicReference<Path> lastPath = new AtomicReference<Path>(); InputStreamConsumer stderrConsumer = new InputStreamConsumer(stderr, (InputStreamConsumer.Handler) line -> { Path path = currentBuildFile.get(); if (!Objects.equals(path, lastPath.get())) { numberOfLines.set(0); lastPath.set(path); } int count = numberOfLines.getAndIncrement(); if (count == 0) { buckEventBus.post(ConsoleEvent.warning("WARNING: Output when parsing %s:", path)); } buckEventBus.post(ConsoleEvent.warning("| %s", line)); }); stderrConsumerTerminationFuture = new FutureTask<>(stderrConsumer); stderrConsumerThread = Threads.namedThread(PythonDslProjectBuildFileParser.class.getSimpleName(), stderrConsumerTerminationFuture); stderrConsumerThread.start(); } }
From source file:com.facebook.buck.cli.TargetPatternEvaluator.java
ImmutableMap<String, ImmutableSet<QueryTarget>> resolveTargetPatterns(Iterable<String> patterns, ListeningExecutorService executor) throws InterruptedException, BuildFileParseException, BuildTargetException, IOException { ImmutableMap.Builder<String, ImmutableSet<QueryTarget>> resolved = ImmutableMap.builder(); Map<String, String> unresolved = new HashMap<>(); for (String pattern : patterns) { // First check if this pattern was resolved before. ImmutableSet<QueryTarget> targets = resolvedTargets.get(pattern); if (targets != null) { resolved.put(pattern, targets); continue; }/*from w w w . j av a2 s. c o m*/ // Check if this is an alias. Set<BuildTarget> aliasTargets = buckConfig.getBuildTargetsForAlias(pattern); if (!aliasTargets.isEmpty()) { for (BuildTarget alias : aliasTargets) { unresolved.put(alias.getFullyQualifiedName(), pattern); } } else { // Check if the pattern corresponds to a build target or a path. if (pattern.contains("//") || pattern.startsWith(":")) { unresolved.put(pattern, pattern); } else { ImmutableSet<QueryTarget> fileTargets = resolveFilePattern(pattern); resolved.put(pattern, fileTargets); resolvedTargets.put(pattern, fileTargets); } } } // Resolve any remaining target patterns using the parser. ImmutableMap<String, ImmutableSet<QueryTarget>> results = MoreMaps.transformKeys( resolveBuildTargetPatterns(ImmutableList.copyOf(unresolved.keySet()), executor), Functions.forMap(unresolved)); resolved.putAll(results); resolvedTargets.putAll(results); return resolved.build(); }
From source file:com.google.devtools.build.lib.rules.cpp.CcCompilationHelper.java
/** * Calculate outputNameMap for different source types separately. Returns a merged outputNameMap * for all artifacts.// w w w .j a va 2 s . co m */ private ImmutableMap<Artifact, String> calculateOutputNameMapByType(Set<CppSource> sources, String prefixDir) { ImmutableMap.Builder<Artifact, String> builder = ImmutableMap.builder(); builder.putAll(calculateOutputNameMap(getSourceArtifactsByType(sources, CppSource.Type.SOURCE), prefixDir)); builder.putAll(calculateOutputNameMap(getSourceArtifactsByType(sources, CppSource.Type.HEADER), prefixDir)); // TODO(plf): Removing CLIF logic builder.putAll(calculateOutputNameMap(getSourceArtifactsByType(sources, CppSource.Type.CLIF_INPUT_PROTO), prefixDir)); return builder.build(); }
From source file:com.facebook.buck.apple.xcode.WorkspaceAndProjectGenerator.java
public Path generateWorkspaceAndDependentProjects(Map<TargetNode<?>, ProjectGenerator> projectGenerators) throws IOException { LOG.debug("Generating workspace for target %s", workspaceTargetNode); String workspaceName;/*from w ww . ja v a 2 s. co m*/ Path outputDirectory; if (combinedProject) { workspaceName = "GeneratedProject"; outputDirectory = Paths.get("_gen"); } else { workspaceName = XcodeWorkspaceConfigDescription .getWorkspaceNameFromArg(workspaceTargetNode.getConstructorArg()); outputDirectory = workspaceTargetNode.getBuildTarget().getBasePath(); } WorkspaceGenerator workspaceGenerator = new WorkspaceGenerator(projectFilesystem, workspaceName, outputDirectory); ImmutableSet<TargetNode<?>> orderedTargetNodes; if (workspaceTargetNode.getConstructorArg().srcTarget.isPresent()) { orderedTargetNodes = AppleBuildRules.getSchemeBuildableTargetNodes(projectGraph, projectGraph.get(workspaceTargetNode.getConstructorArg().srcTarget.get().getBuildTarget())); } else { orderedTargetNodes = ImmutableSet.of(); } ImmutableSet<TargetNode<?>> orderedTestTargetNodes; ImmutableSet<TargetNode<?>> orderedTestBundleTargetNodes; { ImmutableSet.Builder<TargetNode<?>> orderedTestTargetNodesBuilder = ImmutableSet.builder(); ImmutableSet.Builder<TargetNode<?>> orderedTestBundleTargetNodesBuilder = ImmutableSet.builder(); getOrderedTestNodes(projectGraph, sourceTargetToTestNodes, orderedTargetNodes, extraTestBundleTargetNodes, orderedTestTargetNodesBuilder, orderedTestBundleTargetNodesBuilder); orderedTestTargetNodes = orderedTestTargetNodesBuilder.build(); orderedTestBundleTargetNodes = orderedTestBundleTargetNodesBuilder.build(); } ImmutableSet<BuildTarget> targetsInRequiredProjects = FluentIterable .from(Sets.union(orderedTargetNodes, orderedTestTargetNodes)).transform(HasBuildTarget.TO_TARGET) .toSet(); ImmutableMap.Builder<BuildTarget, PBXTarget> buildTargetToPbxTargetMapBuilder = ImmutableMap.builder(); ImmutableMap.Builder<PBXTarget, Path> targetToProjectPathMapBuilder = ImmutableMap.builder(); if (combinedProject) { ImmutableSet.Builder<BuildTarget> initialTargetsBuilder = ImmutableSet.builder(); for (TargetNode<?> targetNode : projectGraph.getNodes()) { if (targetNode.getType() != XcodeProjectConfigDescription.TYPE) { continue; } XcodeProjectConfigDescription.Arg projectArg = (XcodeProjectConfigDescription.Arg) targetNode .getConstructorArg(); if (Sets.intersection(targetsInRequiredProjects, projectArg.rules).isEmpty()) { continue; } initialTargetsBuilder.addAll(projectArg.rules); } LOG.debug("Generating a combined project"); ProjectGenerator generator = new ProjectGenerator(projectGraph, initialTargetsBuilder.build(), projectFilesystem, executionContext, buildRuleResolver, sourcePathResolver, outputDirectory, "GeneratedProject", projectGeneratorOptions); combinedProjectGenerator = Optional.of(generator); generator.createXcodeProjects(); workspaceGenerator.addFilePath(generator.getProjectPath()); buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap()); for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) { targetToProjectPathMapBuilder.put(target, generator.getProjectPath()); } } else { for (TargetNode<?> targetNode : projectGraph.getNodes()) { if (targetNode.getType() != XcodeProjectConfigDescription.TYPE) { continue; } XcodeProjectConfigDescription.Arg projectArg = (XcodeProjectConfigDescription.Arg) targetNode .getConstructorArg(); if (Sets.intersection(targetsInRequiredProjects, projectArg.rules).isEmpty()) { continue; } ProjectGenerator generator = projectGenerators.get(targetNode); if (generator == null) { LOG.debug("Generating project for target %s", targetNode); generator = new ProjectGenerator(projectGraph, projectArg.rules, projectFilesystem, executionContext, buildRuleResolver, sourcePathResolver, targetNode.getBuildTarget().getBasePath(), projectArg.projectName, projectGeneratorOptions); generator.createXcodeProjects(); projectGenerators.put(targetNode, generator); } else { LOG.debug("Already generated project for target %s, skipping", targetNode); } workspaceGenerator.addFilePath(generator.getProjectPath()); buildTargetToPbxTargetMapBuilder.putAll(generator.getBuildTargetToGeneratedTargetMap()); for (PBXTarget target : generator.getBuildTargetToGeneratedTargetMap().values()) { targetToProjectPathMapBuilder.put(target, generator.getProjectPath()); } } } Path workspacePath = workspaceGenerator.writeWorkspace(); SchemeGenerator schemeGenerator = new SchemeGenerator(projectFilesystem, workspaceTargetNode.getConstructorArg().srcTarget, Iterables.transform(orderedTargetNodes, HasBuildTarget.TO_TARGET), Iterables.transform(orderedTestTargetNodes, HasBuildTarget.TO_TARGET), Iterables.transform(orderedTestBundleTargetNodes, HasBuildTarget.TO_TARGET), workspaceName, outputDirectory.resolve(workspaceName + ".xcworkspace"), XcodeWorkspaceConfigDescription .getActionConfigNamesFromArg(workspaceTargetNode.getConstructorArg()), buildTargetToPbxTargetMapBuilder.build(), targetToProjectPathMapBuilder.build()); schemeGenerator.writeScheme(); return workspacePath; }
From source file:com.google.devtools.build.lib.rules.cpp.CcCompilationHelper.java
private CcToolchainVariables setupCompileBuildVariables(CppCompileActionBuilder builder, Label sourceLabel, String outputName, boolean usePic, PathFragment ccRelativeName, PathFragment autoFdoImportPath, CppModuleMap cppModuleMap, Artifact gcnoFile, Artifact dwoFile, Artifact ltoIndexingFile, ImmutableMap<String, String> additionalBuildVariables) { Artifact sourceFile = builder.getSourceFile(); ImmutableList.Builder<String> userCompileFlags = ImmutableList.builder(); userCompileFlags.addAll(getCoptsFromOptions(cppConfiguration, sourceFile.getExecPathString())); userCompileFlags.addAll(copts);/*from w w w . java2 s . co m*/ if (sourceFile != null && sourceLabel != null) { userCompileFlags.addAll(collectPerFileCopts(sourceFile, sourceLabel)); } String dotdFileExecPath = null; if (isGenerateDotdFile(builder.getSourceFile())) { Preconditions.checkNotNull(builder.getDotdFile()); dotdFileExecPath = builder.getDotdFile().getSafeExecPath().getPathString(); } ImmutableMap.Builder<String, String> allAdditionalBuildVariables = ImmutableMap.builder(); allAdditionalBuildVariables.putAll(additionalBuildVariables); if (ccRelativeName != null) { allAdditionalBuildVariables.putAll(fdoSupport.getFdoSupport().configureCompilation(builder, ruleContext, ccRelativeName, autoFdoImportPath, PathFragment.create(outputName), usePic, featureConfiguration, fdoSupport)); } return CompileBuildVariables.setupVariablesOrReportRuleError(ruleContext, featureConfiguration, ccToolchain, toPathString(sourceFile), toPathString(builder.getOutputFile()), toPathString(gcnoFile), toPathString(dwoFile), toPathString(ltoIndexingFile), ImmutableList.of(), userCompileFlags.build(), cppModuleMap, usePic, builder.getTempOutputFile(), CppHelper.getFdoBuildStamp(ruleContext, fdoSupport.getFdoSupport()), dotdFileExecPath, ImmutableList.copyOf(variablesExtensions), allAdditionalBuildVariables.build(), ccCompilationContext.getDirectModuleMaps(), ccCompilationContext.getIncludeDirs(), ccCompilationContext.getQuoteIncludeDirs(), ccCompilationContext.getSystemIncludeDirs(), ccCompilationContext.getDefines()); }