Java Code Examples for com.google.common.collect.ImmutableMap#isEmpty()

The following examples show how to use com.google.common.collect.ImmutableMap#isEmpty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: selenium   File: InternetExplorerFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) {
  ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream()
      .filter(entry ->
                  ("browserName".equals(entry.getKey()) && "internet explorer".equals(entry.getValue())) ||
                  "browserAttachTimeout".equals(entry.getKey()) ||
                  "enableElementCacheCleanup".equals(entry.getKey()) ||
                  "enablePersistentHover".equals(entry.getKey()) ||
                  "extractPath".equals(entry.getKey()) ||
                  "host".equals(entry.getKey()) ||
                  "ignoreZoomSetting".equals(entry.getKey()) ||
                  "initialBrowserZoom".equals(entry.getKey()) ||
                  "logFile".equals(entry.getKey()) ||
                  "logLevel".equals(entry.getKey()) ||
                  "requireWindowFocus".equals(entry.getKey()) ||
                  "se:ieOptions".equals(entry.getKey()) ||
                  "silent".equals(entry.getKey()) ||
                  entry.getKey().startsWith("ie."))
      .distinct()
      .filter(entry -> Objects.nonNull(entry.getValue()))
      .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

  return caps.isEmpty() ? null : caps;
}
 
Example 2
Source Project: bazel   File: ActionExecutionValue.java    License: Apache License 2.0 6 votes vote down vote up
private static <V> ImmutableMap<Artifact, V> transformMap(
    ImmutableMap<Artifact, V> data,
    Map<OwnerlessArtifactWrapper, Artifact> newArtifactMap,
    BiFunction<Artifact, V, V> transform) {
  if (data.isEmpty()) {
    return data;
  }

  ImmutableMap.Builder<Artifact, V> result = ImmutableMap.builderWithExpectedSize(data.size());
  for (Map.Entry<Artifact, V> entry : data.entrySet()) {
    Artifact artifact = entry.getKey();
    Artifact newArtifact =
        Preconditions.checkNotNull(
            newArtifactMap.get(new OwnerlessArtifactWrapper(artifact)),
            "Output artifact %s from one shared action not present in another's outputs (%s)",
            artifact,
            newArtifactMap);
    result.put(newArtifact, transform.apply(newArtifact, entry.getValue()));
  }
  return result.build();
}
 
Example 3
Source Project: bazel   File: DebugEventHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static ImmutableList<Scope> getScopes(ThreadObjectMap objectMap, Debug.Frame frame) {
  Map<String, Object> moduleVars =
      frame.getFunction() instanceof StarlarkFunction
          ? ((StarlarkFunction) frame.getFunction()).getModule().getGlobals()
          : ImmutableMap.of();

  ImmutableMap<String, Object> localVars = frame.getLocals();
  if (localVars.isEmpty()) {
    return ImmutableList.of(getScope(objectMap, "global", moduleVars));
  }

  Map<String, Object> globalVars = new LinkedHashMap<>(moduleVars);
  // remove shadowed bindings
  localVars.keySet().forEach(globalVars::remove);

  return ImmutableList.of(
      getScope(objectMap, "local", localVars), getScope(objectMap, "global", globalVars));
}
 
Example 4
Source Project: buck   File: FileTreeComputation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileTree transform(FileTreeKey key, ComputationEnvironment env) {

  DirectoryList currentDir = env.getDep(ImmutableDirectoryListKey.of(key.getPath()));
  ImmutableMap<FileTreeKey, FileTree> children = env.getDeps(FileTreeKey.IDENTIFIER);

  ImmutableMap<Path, FileTree> deps;
  if (children.isEmpty()) {
    deps = ImmutableMap.of();
  } else {
    // Convert Map<FileTreeKey, FileTree> to Map<Path, FileTree>
    // Not using streams etc. for performance
    // May be instead have FileTree object to have Map<FileTreeKey, FileTree> instead of
    // Map<Path, FileTree>? The interface is less cleaner then, but we can reuse collections

    deps = MoreMaps.transformKeys(children, k -> k.getPath());
  }

  return ImmutableFileTree.of(key.getPath(), currentDir, deps);
}
 
Example 5
Source Project: bazel   File: StarlarkTransition.java    License: Apache License 2.0 5 votes vote down vote up
private static BuildOptions unalias(
    BuildOptions options, ImmutableMap<Label, Label> aliasToActual) {
  if (aliasToActual.isEmpty()) {
    return options;
  }
  Collection<Label> aliases = aliasToActual.keySet();
  Collection<Label> actuals = aliasToActual.values();
  BuildOptions.Builder toReturn = options.toBuilder();
  for (Map.Entry<Label, Object> entry : options.getStarlarkOptions().entrySet()) {
    Label setting = entry.getKey();
    if (actuals.contains(setting)) {
      // if entry is keyed by an actual (e.g. <entry2> in javadoc), don't care about its value
      // it's stale
      continue;
    } else if (aliases.contains(setting)) {
      // if an entry is keyed by an alias (e.g. <entry1> in javadoc), newly key (overwrite) its
      // actual to its alias' value and remove the alias-keyed entry
      toReturn.addStarlarkOption(
          aliasToActual.get(setting), options.getStarlarkOptions().get(setting));
      toReturn.removeStarlarkOption(setting);
    } else {
      // else - just copy over
      toReturn.addStarlarkOption(entry.getKey(), entry.getValue());
    }
  }
  return toReturn.build();
}
 
Example 6
/**
 * Constructs a {@link CollectPackagesUnderDirectoryValue} for a directory without a BUILD file or
 * that has a BUILD file that successfully loads as a package.
 */
public static CollectPackagesUnderDirectoryValue ofNoError(
    boolean isDirectoryPackage,
    ImmutableMap<RootedPath, Boolean> subdirectoryTransitivelyContainsPackagesOrErrors) {
  if (!isDirectoryPackage && subdirectoryTransitivelyContainsPackagesOrErrors.isEmpty()) {
    return NoErrorCollectPackagesUnderDirectoryValue.EMPTY;
  }
  return new NoErrorCollectPackagesUnderDirectoryValue(
      isDirectoryPackage, subdirectoryTransitivelyContainsPackagesOrErrors);
}
 
Example 7
Source Project: selenium   File: EdgeFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) {
  ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream()
      .filter(entry -> ("browserName".equals(entry.getKey()) && "edge".equals(entry.getValue())))
      .distinct()
      .filter(entry -> Objects.nonNull(entry.getValue()))
      .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

  return caps.isEmpty() ? null : caps;
}
 
Example 8
Source Project: VanillaFix   File: MultipartModel.java    License: MIT License 5 votes vote down vote up
@Override
public IModel retexture(ImmutableMap<String, String> textures) {
    if (textures.isEmpty())
        return this;

    ImmutableMap.Builder<Selector, IModel> builder = ImmutableMap.builder();
    for (Map.Entry<Selector, IModel> partModel : partModels.entrySet()) {
        builder.put(partModel.getKey(), partModel.getValue().retexture(textures));
    }

    return new MultipartModel(location, multipart, builder.build());
}
 
Example 9
public static ViewRowFieldNameAndJsonValues ofMap(@NonNull final ImmutableMap<String, Object> map)
{
	if (map.isEmpty())
	{
		return EMPTY;
	}

	return new ViewRowFieldNameAndJsonValues(map);
}
 
Example 10
Source Project: selenium   File: OperaFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> apply(Map<String, Object> unmodifiedCaps) {
  ImmutableMap<String, Object> caps = unmodifiedCaps.entrySet().parallelStream()
      .filter(entry ->
                  ("browserName".equals(entry.getKey()) && "opera".equals(entry.getValue())) ||
                  ("browserName".equals(entry.getKey()) && "operablink".equals(entry.getValue())) ||
                  "operaOptions".equals(entry.getKey()))
      .distinct()
      .filter(entry -> Objects.nonNull(entry.getValue()))
      .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));

  return caps.isEmpty() ? null : caps;
}
 
Example 11
public static <T> Arborescence<T> of(ImmutableMap<T, T> parents) {
    if (parents != null && !parents.isEmpty()) {
        HashSet<T> allParents = Sets.newHashSet(parents.values());
        allParents.removeAll(parents.keySet());
        if (allParents.size() == 1) {
            return new Arborescence<>(parents, allParents.iterator().next());
        }
    }
    return new Arborescence<>(parents, null);
}
 
Example 12
Source Project: glowroot   File: AdviceCache.java    License: Apache License 2.0 5 votes vote down vote up
private static ImmutableList<Advice> createReweavableAdvisors(
        List<InstrumentationConfig> reweavableConfigs,
        @Nullable Instrumentation instrumentation, File tmpDir, boolean cleanTmpDir)
        throws Exception {
    ImmutableMap<Advice, LazyDefinedClass> advisors =
            AdviceGenerator.createAdvisors(reweavableConfigs, null, false, true);
    if (instrumentation == null) {
        // instrumentation is null when debugging with LocalContainer
        ClassLoader isolatedWeavingClassLoader =
                Thread.currentThread().getContextClassLoader();
        checkNotNull(isolatedWeavingClassLoader);
        ClassLoaders.defineClasses(advisors.values(), isolatedWeavingClassLoader);
    } else {
        if (cleanTmpDir) {
            ClassLoaders.createDirectoryOrCleanPreviousContentsWithPrefix(tmpDir,
                    "config-pointcuts");
        }
        if (!advisors.isEmpty()) {
            String suffix = "";
            int count = jarFileCounter.incrementAndGet();
            if (count > 1) {
                suffix = "-" + count;
            }
            File jarFile = new File(tmpDir, "config-pointcuts" + suffix + ".jar");
            ClassLoaders.defineClassesInBootstrapClassLoader(advisors.values(), instrumentation,
                    jarFile);
        }
    }
    return advisors.keySet().asList();
}
 
Example 13
Source Project: bazel   File: LtoCompilationContext.java    License: Apache License 2.0 5 votes vote down vote up
public LtoCompilationContext build() {
  ImmutableMap<Artifact, BitcodeInfo> map = ltoBitcodeFiles.build();
  if (map.isEmpty()) {
    return LtoCompilationContext.EMPTY;
  }
  return new LtoCompilationContext(map);
}
 
Example 14
Source Project: nomulus   File: CommitLoggedWork.java    License: Apache License 2.0 5 votes vote down vote up
/** Check that the timestamp of each BackupGroupRoot is in the past. */
private void checkBackupGroupRootTimestamps(
    DateTime transactionTime, Set<Entry<Key<BackupGroupRoot>, BackupGroupRoot>> bgrEntries) {
  ImmutableMap.Builder<Key<BackupGroupRoot>, DateTime> builder = new ImmutableMap.Builder<>();
  for (Entry<Key<BackupGroupRoot>, BackupGroupRoot> entry : bgrEntries) {
    DateTime updateTime = entry.getValue().getUpdateAutoTimestamp().getTimestamp();
    if (!updateTime.isBefore(transactionTime)) {
      builder.put(entry.getKey(), updateTime);
    }
  }
  ImmutableMap<Key<BackupGroupRoot>, DateTime> problematicRoots = builder.build();
  if (!problematicRoots.isEmpty()) {
    throw new TimestampInversionException(transactionTime, problematicRoots);
  }
}
 
Example 15
private void submitLimiterStopMetadataEvents (){
  ImmutableMap<String, String> metaData = this.getLimiterStopMetadata();
  if (!metaData.isEmpty()) {
    this.eventSubmitter.submit(LIMITER_STOP_EVENT_NAME, metaData);
  }
}
 
Example 16
Source Project: buck   File: CxxLinkableEnhancer.java    License: Apache License 2.0 4 votes vote down vote up
public static CxxLink createCxxLinkableBuildRule(
    CellPathResolver cellPathResolver,
    CxxBuckConfig cxxBuckConfig,
    CxxPlatform cxxPlatform,
    ProjectFilesystem projectFilesystem,
    BuildRuleResolver ruleResolver,
    BuildTarget target,
    Path output,
    ImmutableMap<String, Path> extraOutputs,
    ImmutableList<Arg> args,
    LinkableDepType runtimeDepType,
    CxxLinkOptions linkOptions,
    Optional<LinkOutputPostprocessor> postprocessor) {

  Linker linker = cxxPlatform.getLd().resolve(ruleResolver, target.getTargetConfiguration());

  // Build up the arguments to pass to the linker.
  ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

  // Add flags to generate linker map if supported.
  if (linker instanceof HasLinkerMap && LinkerMapMode.isLinkerMapEnabledForBuildTarget(target)) {
    argsBuilder.addAll(((HasLinkerMap) linker).linkerMap(output));
  }

  // Add lto object path if thin LTO is on.
  if (linker instanceof HasLTO && linkOptions.getThinLto()) {
    argsBuilder.addAll(((HasLTO) linker).thinLTO(output));
  } else if (linker instanceof HasLTO && linkOptions.getFatLto()) {
    argsBuilder.addAll(((HasLTO) linker).fatLTO(output));
  }

  if (linker instanceof HasImportLibrary) {
    argsBuilder.addAll(((HasImportLibrary) linker).importLibrary(output));
  }

  // Pass any platform specific or extra linker flags.
  argsBuilder.addAll(
      SanitizedArg.fromArgs(
          cxxPlatform.getCompilerDebugPathSanitizer().sanitizer(Optional.empty()),
          cxxPlatform.getLdflags()));

  argsBuilder.addAll(args);

  // Add all arguments needed to link in the C/C++ platform runtime.
  argsBuilder.addAll(cxxPlatform.getRuntimeLdflags().get(runtimeDepType));

  ImmutableList<Arg> ldArgs = argsBuilder.build();
  ImmutableMap<String, Path> allExtraOutputs = extraOutputs;

  Optional<ExtraOutputsDeriver> extraOutputsDeriver = linker.getExtraOutputsDeriver();
  if (extraOutputsDeriver.isPresent()) {
    ImmutableMap<String, Path> derivedExtraOutputs =
        extraOutputsDeriver
            .get()
            .deriveExtraOutputsFromArgs(
                Arg.stringify(ldArgs, ruleResolver.getSourcePathResolver()), output);
    if (!derivedExtraOutputs.isEmpty()) {
      allExtraOutputs =
          ImmutableMap.<String, Path>builder()
              .putAll(extraOutputs)
              .putAll(derivedExtraOutputs)
              .build();
    }
  }

  return new CxxLink(
      target,
      projectFilesystem,
      ruleResolver,
      cellPathResolver,
      linker,
      output,
      allExtraOutputs,
      ldArgs,
      postprocessor,
      cxxBuckConfig.getLinkScheduleInfo(),
      cxxBuckConfig.shouldCacheLinks(),
      linkOptions.getThinLto(),
      linkOptions.getFatLto());
}
 
Example 17
Source Project: james-project   File: MessageFullView.java    License: Apache License 2.0 4 votes vote down vote up
protected static boolean areAttachedMessagesKeysInAttachments(ImmutableList<Attachment> attachments, ImmutableMap<BlobId, SubMessage> attachedMessages) {
    return attachedMessages.isEmpty() || attachedMessages.keySet().stream()
            .anyMatch(inAttachments(attachments));
}
 
Example 18
Source Project: buck   File: BuckConfig.java    License: Apache License 2.0 4 votes vote down vote up
public Optional<ImmutableMap<String, String>> getSection(String sectionName) {
  ImmutableMap<String, String> values = config.get(sectionName);
  return values.isEmpty() ? Optional.empty() : Optional.of(values);
}
 
Example 19
Source Project: buck   File: JavaBinaryDescription.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public BuildRule createBuildRule(
    BuildRuleCreationContextWithTargetGraph context,
    BuildTarget buildTarget,
    BuildRuleParams params,
    JavaBinaryDescriptionArg args) {

  ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
  ImmutableMap<String, SourcePath> nativeLibraries =
      JavaLibraryRules.getNativeLibraries(
          params.getBuildDeps(),
          getCxxPlatform(args, buildTarget.getTargetConfiguration())
              .resolve(graphBuilder, buildTarget.getTargetConfiguration()),
          context.getActionGraphBuilder());
  BuildTarget binaryBuildTarget = buildTarget;

  // If we're packaging native libraries, we'll build the binary JAR in a separate rule and
  // package it into the final fat JAR, so adjust it's params to use a flavored target.
  if (!nativeLibraries.isEmpty()) {
    binaryBuildTarget = binaryBuildTarget.withAppendedFlavors(FAT_JAR_INNER_JAR_FLAVOR);
  }

  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

  // Construct the build rule to build the binary JAR.
  ImmutableSet<JavaLibrary> transitiveClasspathDeps =
      JavaLibraryClasspathProvider.getClasspathDeps(params.getBuildDeps());
  ImmutableSet<SourcePath> transitiveClasspaths =
      JavaLibraryClasspathProvider.getClasspathsFromLibraries(transitiveClasspathDeps);
  JavaBinary javaBinary =
      new JavaBinary(
          binaryBuildTarget,
          projectFilesystem,
          params.copyAppendingExtraDeps(transitiveClasspathDeps),
          javaOptions
              .apply(buildTarget.getTargetConfiguration())
              .getJavaRuntimeLauncher(graphBuilder, buildTarget.getTargetConfiguration()),
          args.getMainClass().orElse(null),
          args.getManifestFile().orElse(null),
          args.getMergeManifests().orElse(true),
          args.getDisallowAllDuplicates().orElse(false),
          args.getMetaInfDirectory().orElse(null),
          args.getBlacklist(),
          transitiveClasspathDeps,
          transitiveClasspaths,
          javaBuckConfig.shouldCacheBinaries(),
          javaBuckConfig.getDuplicatesLogLevel());

  // If we're packaging native libraries, construct the rule to build the fat JAR, which packages
  // up the original binary JAR and any required native libraries.
  BuildRule rule;
  if (nativeLibraries.isEmpty()) {
    rule = javaBinary;
  } else {
    graphBuilder.addToIndex(javaBinary);
    SourcePath innerJar = javaBinary.getSourcePathToOutput();
    JavacFactory javacFactory = JavacFactory.getDefault(toolchainProvider);
    rule =
        new JarFattener(
            buildTarget,
            projectFilesystem,
            params.copyAppendingExtraDeps(
                Suppliers.<Iterable<BuildRule>>ofInstance(
                    Iterables.concat(
                        graphBuilder.filterBuildRuleInputs(
                            ImmutableList.<SourcePath>builder()
                                .add(innerJar)
                                .addAll(nativeLibraries.values())
                                .build()),
                        javacFactory.getBuildDeps(
                            graphBuilder, binaryBuildTarget.getTargetConfiguration())))),
            javacFactory.create(graphBuilder, null, binaryBuildTarget.getTargetConfiguration()),
            toolchainProvider
                .getByName(
                    JavacOptionsProvider.DEFAULT_NAME,
                    binaryBuildTarget.getTargetConfiguration(),
                    JavacOptionsProvider.class)
                .getJavacOptions(),
            innerJar,
            javaBinary,
            nativeLibraries,
            javaOptions
                .apply(buildTarget.getTargetConfiguration())
                .getJavaRuntimeLauncher(graphBuilder, buildTarget.getTargetConfiguration()));
  }

  return rule;
}
 
Example 20
Source Project: buck   File: TargetsCommand.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Wrapper method for {@link #getOutputPathsByLabels} to make the return type {@link Optional}
 * so empty lists and empty maps won't be printed in the JSON output. {@link
 * #getOutputPathsByLabels} isn't Optional to make it easy to interact with while building (i.e.
 * to have access to #putOutputPathsByLabels from codegen).
 */
public Optional<ImmutableMap<OutputLabel, ImmutableSet<String>>> getOutputPaths() {
  ImmutableMap<OutputLabel, ImmutableSet<String>> result = getOutputPathsByLabels();
  return result.isEmpty() ? Optional.empty() : Optional.of(result);
}