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

The following examples show how to use com.google.common.collect.ImmutableMap#getOrDefault() . 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 File: PackageFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static int getOriginalWorkspaceChunk(
    Environment env, RootedPath workspacePath, int workspaceChunk, Label loadLabel)
    throws InterruptedException {
  if (workspaceChunk < 1) {
    return workspaceChunk;
  }
  // If we got here, we are already computing workspaceChunk "workspaceChunk", and so we know
  // that the value for "workspaceChunk-1" has already been computed so we don't need to check
  // for nullness
  SkyKey workspaceFileKey = WorkspaceFileValue.key(workspacePath, workspaceChunk - 1);
  WorkspaceFileValue workspaceFileValue = (WorkspaceFileValue) env.getValue(workspaceFileKey);
  ImmutableMap<String, Integer> loadToChunkMap = workspaceFileValue.getLoadToChunkMap();
  String loadString = loadLabel.toString();
  return loadToChunkMap.getOrDefault(loadString, workspaceChunk);
}
 
Example 2
Source File: PackageIdentifier.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static PackageIdentifier parse(
    String input, String repo, ImmutableMap<RepositoryName, RepositoryName> repositoryMapping)
    throws LabelSyntaxException {
  String packageName;
  int packageStartPos = input.indexOf("//");
  if (repo != null) {
    packageName = input;
  } else if (input.startsWith("@") && packageStartPos > 0) {
    repo = input.substring(0, packageStartPos);
    packageName = input.substring(packageStartPos + 2);
  } else if (input.startsWith("@")) {
    throw new LabelSyntaxException("starts with a '@' but does not contain '//'");
  } else if (packageStartPos == 0) {
    repo = RepositoryName.DEFAULT_REPOSITORY;
    packageName = input.substring(2);
  } else {
    repo = RepositoryName.DEFAULT_REPOSITORY;
    packageName = input;
  }

  String error = RepositoryName.validate(repo);
  if (error != null) {
    throw new LabelSyntaxException(error);
  }

  error = LabelValidator.validatePackageName(packageName);
  if (error != null) {
    throw new LabelSyntaxException(error);
  }

  if (repositoryMapping != null) {
    RepositoryName repositoryName = RepositoryName.create(repo);
    repositoryName = repositoryMapping.getOrDefault(repositoryName, repositoryName);
    return create(repositoryName, PathFragment.create(packageName));
  } else {
    return create(repo, PathFragment.create(packageName));
  }
}
 
Example 3
Source File: Label.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static RepositoryName getGlobalRepoName(
    String repo, ImmutableMap<RepositoryName, RepositoryName> repositoryMapping)
    throws LabelSyntaxException {
  Preconditions.checkNotNull(repositoryMapping);
  RepositoryName repoName = RepositoryName.create(repo);
  return repositoryMapping.getOrDefault(repoName, repoName);
}
 
Example 4
Source File: RemoteExecutionConsoleLineProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
private int getLocallyBuiltRules(
    int totalBuildRules, ImmutableMap<State, Integer> actionsPerState) {
  int remotelyExecutedBuildRules =
      actionsPerState.getOrDefault(State.ACTION_SUCCEEDED, 0)
          + actionsPerState.getOrDefault(State.ACTION_FAILED, 0);
  return Math.max(0, totalBuildRules - remotelyExecutedBuildRules);
}
 
Example 5
Source File: RemoteExecutionConsoleLineProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
private static String getStatesString(ImmutableMap<State, Integer> actionsPerState) {
  List<String> states = Lists.newArrayList();
  for (State state : RemoteExecutionActionEvent.State.values()) {
    String stateName = state.getAbbreviateName();
    Integer stateValue = actionsPerState.getOrDefault(state, 0);
    states.add(String.format("%s=%d", stateName, stateValue));
  }

  return Joiner.on(" ").join(states);
}
 
Example 6
Source File: ConfigIgnoredByDaemon.java    From buck with Apache License 2.0 5 votes vote down vote up
@Value.Lazy
public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() {
  ImmutableMap<String, ImmutableSet<String>> ignoredFields = getIgnoreFieldsForDaemonRestart();
  ImmutableMap<String, ImmutableMap<String, String>> rawSections =
      getDelegate().getConfig().getSectionToEntries();

  // If the raw config doesn't have sections which have ignored fields, then just return it as-is.
  ImmutableSet<String> sectionsWithIgnoredFields = ignoredFields.keySet();
  if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) {
    return rawSections;
  }

  // Otherwise, iterate through the config to do finer-grain filtering.
  ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder();
  for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) {
    String sectionName = sectionEnt.getKey();

    // If this section doesn't have a corresponding ignored section, then just add it as-is.
    if (!sectionsWithIgnoredFields.contains(sectionName)) {
      filtered.put(sectionEnt);
      continue;
    }

    // If none of this section's entries are ignored, then add it as-is.
    ImmutableMap<String, String> fields = sectionEnt.getValue();
    ImmutableSet<String> ignoredFieldNames =
        ignoredFields.getOrDefault(sectionName, ImmutableSet.of());
    if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) {
      filtered.put(sectionEnt);
      continue;
    }

    // Otherwise, filter out the ignored fields.
    ImmutableMap<String, String> remainingKeys =
        ImmutableMap.copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains)));
    filtered.put(sectionName, remainingKeys);
  }

  return MoreMaps.filterValues(filtered.build(), Predicates.not(Map::isEmpty));
}
 
Example 7
Source File: ProguardSuggester.java    From size-analyzer with Apache License 2.0 4 votes vote down vote up
@Override
public ImmutableList<Suggestion> processProject(GradleContext context, File projectDir) {
  if (context.getPluginType() != GradleContext.PluginType.APPLICATION) {
    // dynamic-features and root build.gradle files do not contain the proguard configuration
    // being used.
    return ImmutableList.of();
  }
  ImmutableMap<String, ProguardConfig> proguardConfigs = context.getProguardConfigs();
  ProguardConfig proguardConfig =
      proguardConfigs.getOrDefault(
          "release", proguardConfigs.getOrDefault(ProguardConfig.DEFAULT_CONFIG_NAME, null));
  if (proguardConfig == null || !proguardConfig.getHasProguardRules()) {
    return ImmutableList.of(
        Suggestion.create(
            IssueType.PROGUARD_NO_SHRINKING,
            Category.PROGUARD,
            Payload.getDefaultInstance(),
            NO_CODE_SHRINKING,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null),
        Suggestion.create(
            IssueType.PROGUARD_NO_OBFUSCATION,
            Category.PROGUARD,
            Payload.getDefaultInstance(),
            NO_OBFUSCATION,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }
  ImmutableList.Builder<Suggestion> suggestions = ImmutableList.<Suggestion>builder();
  if (!proguardConfig.getMinifyEnabled()) {
    suggestions.add(
        Suggestion.create(
            IssueType.PROGUARD_NO_SHRINKING,
            Category.PROGUARD,
            Payload.getDefaultInstance(),
            NO_CODE_SHRINKING,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }
  if (!proguardConfig.getObfuscationEnabled()) {
    suggestions.add(
        Suggestion.create(
            IssueType.PROGUARD_NO_OBFUSCATION,
            Category.PROGUARD,
            Payload.getDefaultInstance(),
            NO_OBFUSCATION,
            /* estimatedBytesSaved= */ null,
            /* autoFix= */ null));
  }
  return suggestions.build();
}
 
Example 8
Source File: ManifestDeliveryElement.java    From bundletool with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all module conditions.
 *
 * <p>We support <dist:min-sdk-version>, <dist:device-feature> and <dist:user-countries>
 * conditions today. Any other conditions types are not supported and will result in {@link
 * InvalidBundleException}.
 */
@Memoized
public ModuleConditions getModuleConditions() {
  ImmutableList<XmlProtoElement> conditionElements = getModuleConditionElements();

  ImmutableMap<String, Long> conditionCounts =
      conditionElements.stream()
          .collect(groupingByDeterministic(XmlProtoElement::getName, counting()));
  for (String conditionName : CONDITIONS_ALLOWED_ONLY_ONCE) {
    if (conditionCounts.getOrDefault(conditionName, 0L) > 1) {
      throw InvalidBundleException.builder()
          .withUserMessage("Multiple '<dist:%s>' conditions are not supported.", conditionName)
          .build();
    }
  }

  ModuleConditions.Builder moduleConditions = ModuleConditions.builder();
  for (XmlProtoElement conditionElement : conditionElements) {
    if (!conditionElement.getNamespaceUri().equals(DISTRIBUTION_NAMESPACE_URI)) {
      throw InvalidBundleException.builder()
          .withUserMessage(
              "Invalid namespace found in the module condition element. "
                  + "Expected '%s'; found '%s'.",
              DISTRIBUTION_NAMESPACE_URI, conditionElement.getNamespaceUri())
          .build();
    }
    switch (conditionElement.getName()) {
      case CONDITION_DEVICE_FEATURE_NAME:
        moduleConditions.addDeviceFeatureCondition(parseDeviceFeatureCondition(conditionElement));
        break;
      case CONDITION_MIN_SDK_VERSION_NAME:
        moduleConditions.setMinSdkVersion(parseMinSdkVersionCondition(conditionElement));
        break;
      case CONDITION_MAX_SDK_VERSION_NAME:
        moduleConditions.setMaxSdkVersion(parseMaxSdkVersionCondition(conditionElement));
        break;
      case CONDITION_USER_COUNTRIES_NAME:
        moduleConditions.setUserCountriesCondition(parseUserCountriesCondition(conditionElement));
        break;
      default:
        throw InvalidBundleException.builder()
            .withUserMessage("Unrecognized module condition: '%s'", conditionElement.getName())
            .build();
    }
  }

  ModuleConditions processedModuleConditions = moduleConditions.build();

  if (processedModuleConditions.getMinSdkVersion().isPresent()
      && processedModuleConditions.getMaxSdkVersion().isPresent()) {
    if (processedModuleConditions.getMinSdkVersion().get()
        > processedModuleConditions.getMaxSdkVersion().get()) {
      throw InvalidBundleException.builder()
          .withUserMessage(
              "Illegal SDK-based conditional module targeting (min SDK must be less than or"
                  + " equal to max SD). Provided min and max values, respectively, are %s and %s",
              processedModuleConditions.getMinSdkVersion(),
              processedModuleConditions.getMaxSdkVersion())
          .build();
    }
  }

  return processedModuleConditions;
}
 
Example 9
Source File: RemoteExecutionConsoleLineProvider.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public ImmutableList<String> createConsoleLinesAtTime(long currentTimeMillis) {
  ImmutableList.Builder<String> lines = ImmutableList.builder();
  ImmutableMap<RemoteExecutionActionEvent.State, Integer> actionsPerState =
      statsProvider.getActionsPerState();
  if (!hasFirstRemoteActionStarted(actionsPerState)) {
    return lines.build();
  }
  if (isDebug) {
    String metadataLine = String.format("[RE] Metadata: Session ID=[%s]", sessionIdInfo);
    lines.add(metadataLine);

    String actionsLine =
        String.format(
            "[RE] Actions: Local=%d Remote=[%s]",
            getLocallyBuiltRules(statsProvider.getTotalRulesBuilt(), actionsPerState),
            getStatesString(actionsPerState));
    lines.add(actionsLine);

    String casLine =
        String.format(
            "[RE] CAS: Upl=[Count:%d Size=%s] Dwl=[Count:%d Size=%s]",
            statsProvider.getCasUploads(),
            prettyPrintSize(statsProvider.getCasUploadSizeBytes()),
            statsProvider.getCasDownloads(),
            prettyPrintSize(statsProvider.getCasDownloadSizeBytes()));
    lines.add(casLine);

    long remoteCpuMs = statsProvider.getRemoteCpuTimeMs();
    long minutesCpu = TimeUnit.MILLISECONDS.toMinutes(remoteCpuMs);
    String metricsLine =
        String.format(
            "[RE] Metrics: CPU %d:%02d minutes",
            minutesCpu,
            TimeUnit.MILLISECONDS.toSeconds(remoteCpuMs)
                - TimeUnit.MINUTES.toSeconds(minutesCpu));
    lines.add(metricsLine);
  }
  if (statsProvider.getTotalRemoteTimeMs() > 0) {
    long remoteTotalMs = statsProvider.getTotalRemoteTimeMs();
    long minutesTotal = TimeUnit.MILLISECONDS.toMinutes(remoteTotalMs);
    lines.add(
        String.format(
            "Building with Remote Execution [RE]. Used %d:%02d minutes of total time.",
            minutesTotal,
            TimeUnit.MILLISECONDS.toSeconds(remoteTotalMs)
                - TimeUnit.MINUTES.toSeconds(minutesTotal)));
    int waitingActions = 0;
    for (State state : RemoteExecutionActionEvent.State.values()) {
      if (!RemoteExecutionActionEvent.isTerminalState(state)) {
        waitingActions += actionsPerState.getOrDefault(state, 0);
      }
    }
    lines.add(
        String.format(
            "[RE] Waiting on %d remote actions. Completed %d actions remotely.",
            waitingActions, actionsPerState.getOrDefault(State.ACTION_SUCCEEDED, 0)));
  }
  LocalFallbackStats localFallbackStats = statsProvider.getLocalFallbackStats();
  if (localFallbackStats.getLocallyExecutedRules() > 0) {
    float percentageRetry =
        (100f * localFallbackStats.getLocallyExecutedRules())
            / localFallbackStats.getTotalExecutedRules();
    lines.add(
        String.format(
            "[RE] Some actions failed remotely, retrying locally. LocalFallback: [fallback_rate=%.2f%% remote=%d local=%d]",
            percentageRetry,
            localFallbackStats.getTotalExecutedRules()
                - localFallbackStats.getLocallyExecutedRules(),
            localFallbackStats.getLocallySuccessfulRules()));
  }

  return lines.build();
}