Java Code Examples for com.google.common.collect.ImmutableSortedMap#Builder

The following examples show how to use com.google.common.collect.ImmutableSortedMap#Builder . 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: Resolver.java    From buck with Apache License 2.0 6 votes vote down vote up
private ImmutableMap<String, Artifact> getRunTimeTransitiveDeps(Iterable<Dependency> mavenCoords)
    throws RepositoryException {

  CollectRequest collectRequest = new CollectRequest();
  collectRequest.setRequestContext(JavaScopes.RUNTIME);
  collectRequest.setRepositories(repos);

  for (Dependency dep : mavenCoords) {
    collectRequest.addDependency(dep);
  }

  DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
  DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, filter);

  DependencyResult dependencyResult = repoSys.resolveDependencies(session, dependencyRequest);

  ImmutableSortedMap.Builder<String, Artifact> knownDeps = ImmutableSortedMap.naturalOrder();
  for (ArtifactResult artifactResult : dependencyResult.getArtifactResults()) {
    Artifact node = artifactResult.getArtifact();
    knownDeps.put(buildKey(node), node);
  }
  return knownDeps.build();
}
 
Example 2
Source File: PColumnFamilyImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public PColumnFamilyImpl(PName name, List<PColumn> columns) {
    Preconditions.checkNotNull(name);
    // Include guidePosts also in estimating the size
    long estimatedSize = SizedUtil.OBJECT_SIZE + SizedUtil.POINTER_SIZE * 5 + SizedUtil.INT_SIZE + name.getEstimatedSize() +
            SizedUtil.sizeOfMap(columns.size()) * 2 + SizedUtil.sizeOfArrayList(columns.size());
    this.name = name;
    this.columns = ImmutableList.copyOf(columns);
    ImmutableMap.Builder<String, PColumn> columnByStringBuilder = ImmutableMap.builder();
    ImmutableSortedMap.Builder<byte[], PColumn> columnByBytesBuilder = ImmutableSortedMap.orderedBy(Bytes.BYTES_COMPARATOR);
    for (PColumn column : columns) {
        estimatedSize += column.getEstimatedSize();
        columnByBytesBuilder.put(column.getName().getBytes(), column);
        columnByStringBuilder.put(column.getName().getString(), column);
    }
    this.columnByBytes = columnByBytesBuilder.build();
    this.columnByString = columnByStringBuilder.build();
    this.estimatedSize = (int)estimatedSize;
}
 
Example 3
Source File: MultiThreadedActionGraphBuilder.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ImmutableSortedMap<BuildTarget, BuildRule> computeAllIfAbsent(
    ImmutableMap<BuildTarget, Function<BuildTarget, BuildRule>> mappings) {
  ImmutableSortedMap.Builder<BuildTarget, BuildRule> resultBuilder =
      ImmutableSortedMap.naturalOrder();
  transformParallel(
      mappings.entrySet(),
      entry ->
          buildRuleIndex.computeIfAbsent(
              entry.getKey(),
              ignored ->
                  new Task<>(
                      () -> withCorrectTargetCheck(entry.getValue()).apply(entry.getKey()))),
      (entry, rule) -> resultBuilder.put(entry.getKey(), rule));
  return resultBuilder.build();
}
 
Example 4
Source File: PythonUtil.java    From buck with Apache License 2.0 6 votes vote down vote up
public static ImmutableSortedMap<Path, SourcePath> parseResources(
    BuildTarget target,
    ActionGraphBuilder graphBuilder,
    PythonPlatform pythonPlatform,
    CxxPlatform cxxPlatform,
    Optional<ImmutableMap<BuildTarget, Version>> versions,
    PythonLibraryDescription.CoreArg args) {
  ImmutableSortedMap.Builder<Path, SourcePath> builder = ImmutableSortedMap.naturalOrder();
  forEachModule(
      target,
      graphBuilder,
      pythonPlatform,
      cxxPlatform,
      "resources",
      PythonUtil.getBasePath(target, args.getBaseModule()),
      args.getResources(),
      args.getPlatformResources(),
      args.getVersionedResources(),
      versions,
      builder::put);
  return builder.build();
}
 
Example 5
Source File: AppleDescriptions.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Convert {@link SourcePath} to a mapping of {@code include path -> file path}.
 *
 * <p>{@code include path} is the path that can be referenced in {@code #include} directives.
 * {@code file path} is the actual path to the file on disk.
 *
 * @throws HumanReadableException when two {@code SourcePath} yields the same IncludePath.
 */
@VisibleForTesting
static ImmutableSortedMap<String, SourcePath> convertToFlatCxxHeaders(
    BuildTarget buildTarget,
    Path headerPathPrefix,
    Function<SourcePath, Path> sourcePathResolver,
    Set<SourcePath> headerPaths) {
  Set<String> includeToFile = new HashSet<String>(headerPaths.size());
  ImmutableSortedMap.Builder<String, SourcePath> builder = ImmutableSortedMap.naturalOrder();
  for (SourcePath headerPath : headerPaths) {
    Path fileName = sourcePathResolver.apply(headerPath).getFileName();
    String key = headerPathPrefix.resolve(fileName).toString();
    if (includeToFile.contains(key)) {
      ImmutableSortedMap<String, SourcePath> result = builder.build();
      throw new HumanReadableException(
          "In target '%s', '%s' maps to the following header files:\n"
              + "- %s\n"
              + "- %s\n\n"
              + "Please rename one of them or export one of them to a different path.",
          buildTarget, key, headerPath, result.get(key));
    }
    includeToFile.add(key);
    builder.put(key, headerPath);
  }
  return builder.build();
}
 
Example 6
Source File: AndroidMultiPlatformRule.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public Platform createPlatform(
    RuleBasedPlatformResolver ruleBasedPlatformResolver, DependencyStack dependencyStack) {
  Platform basePlatform =
      ruleBasedPlatformResolver.getPlatform(this.basePlatform, dependencyStack);

  ImmutableSortedMap.Builder<TargetCpuType, NamedPlatform> nestedPlatforms =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<TargetCpuType, BuildTarget> e : this.nestedPlatforms.entrySet()) {
    nestedPlatforms.put(
        e.getKey(),
        ruleBasedPlatformResolver.getPlatform(e.getValue(), dependencyStack.child(e.getValue())));
  }

  return new AndroidMultiPlatform(getBuildTarget(), basePlatform, nestedPlatforms.build());
}
 
Example 7
Source File: BuildFileManifestPojoizer.java    From buck with Apache License 2.0 5 votes vote down vote up
private ImmutableMap<Object, Object> convertMapToPojo(Object object) {
  @SuppressWarnings("unchecked")
  Map<Object, Object> map = (Map<Object, Object>) object;

  boolean needConversion;
  ImmutableMap.Builder<Object, Object> builder;
  if (map instanceof SortedMap) {
    needConversion = !(map instanceof ImmutableSortedMap);
    builder = new ImmutableSortedMap.Builder<>(((SortedMap<Object, Object>) map).comparator());
  } else {
    needConversion = !(map instanceof ImmutableMap);
    builder = ImmutableMap.builderWithExpectedSize(map.size());
  }

  for (Map.Entry<?, ?> entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    Object convertedKey = convertToPojo(key);
    Object convertedValue = convertToPojo(value);

    if (!needConversion && (convertedKey != key || convertedValue != value)) {
      needConversion = true;
    }

    builder.put(convertedKey, convertedValue);
  }
  return needConversion ? builder.build() : (ImmutableMap<Object, Object>) map;
}
 
Example 8
Source File: NinjaTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedMap<String, String> computeInputOutputVariables() {
  ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
  String inNewline =
      inputs.get(InputKind.EXPLICIT).stream()
          .map(PathFragment::getPathString)
          .collect(Collectors.joining("\n"));
  String out =
      outputs.get(OutputKind.EXPLICIT).stream()
          .map(PathFragment::getPathString)
          .collect(Collectors.joining(" "));
  builder.put("in", inNewline.replace('\n', ' '));
  builder.put("in_newline", inNewline);
  builder.put("out", out);
  return builder.build();
}
 
Example 9
Source File: SimpleCalciteSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected void addImplicitSubSchemaToBuilder(
    ImmutableSortedMap.Builder<String, CalciteSchema> builder) {
  ImmutableSortedMap<String, CalciteSchema> explicitSubSchemas = builder.build();
  for (String schemaName : schema.getSubSchemaNames()) {
    if (explicitSubSchemas.containsKey(schemaName)) {
      // explicit subschema wins.
      continue;
    }
    Schema s = schema.getSubSchema(schemaName);
    if (s != null) {
      CalciteSchema calciteSchema = new SimpleCalciteSchema(this, s, schemaName);
      builder.put(schemaName, calciteSchema);
    }
  }
}
 
Example 10
Source File: ImmutableWeightedRandomChooser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Construct a chooser with the given items
 * @param weights Map of items to weights
 */
public ImmutableWeightedRandomChooser(Map<T, N> weights) {
    final ImmutableSortedMap.Builder<Double, Option> builder = ImmutableSortedMap.naturalOrder();
    double total = 0;
    for(Map.Entry<T, N> entry : weights.entrySet()) {
        double weight = entry.getValue().doubleValue();
        if(weight > 0) {
            total += weight;
            builder.put(total, new Option(entry.getKey(), weight));
        }
    }
    this.options = builder.build();
    this.totalWeight = total;
}
 
Example 11
Source File: NinjaActionsHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static ImmutableSortedMap<String, String> createExecutionInfo(RuleContext ruleContext) {
  ImmutableSortedMap.Builder<String, String> builder = ImmutableSortedMap.naturalOrder();
  builder.putAll(TargetUtils.getExecutionInfo(ruleContext.getRule()));
  builder.put("local", "");
  ImmutableSortedMap<String, String> map = builder.build();
  Preconditions.checkNotNull(ruleContext.getConfiguration())
      .modifyExecutionInfo(map, "NinjaRule");
  return map;
}
 
Example 12
Source File: NinjaTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map from rule variable to fully-expanded value, for all rule variables defined in
 * this target.
 */
public ImmutableSortedMap<NinjaRuleVariable, String> computeRuleVariables() {
  ImmutableSortedMap<String, String> lateExpansionVariables = computeInputOutputVariables();
  ImmutableSortedMap.Builder<String, String> fullExpansionVariablesBuilder =
      ImmutableSortedMap.<String, String>naturalOrder().putAll(lateExpansionVariables);

  ImmutableSortedMap.Builder<NinjaRuleVariable, String> builder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<NinjaRuleVariable, NinjaVariableValue> entry : ruleVariables.entrySet()) {
    NinjaRuleVariable type = entry.getKey();
    // Skip command for now. It may need to expand other rule variables.
    if (NinjaRuleVariable.COMMAND.equals(type)) {
      continue;
    }

    String expandedValue = entry.getValue().expandValue(lateExpansionVariables);
    builder.put(type, expandedValue);
    fullExpansionVariablesBuilder.put(Ascii.toLowerCase(type.name()), expandedValue);
  }

  // TODO(cparsons): Ensure parsing exception is thrown early if the rule has no command defined.
  // Otherwise, this throws NPE.
  String expandedCommand =
      ruleVariables
          .get(NinjaRuleVariable.COMMAND)
          .expandValue(fullExpansionVariablesBuilder.build());
  builder.put(NinjaRuleVariable.COMMAND, expandedCommand);
  return builder.build();
}
 
Example 13
Source File: Match.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates an immutable map of a map of sorted sets. */
private static <K extends Comparable<K>, V> ImmutableSortedMap<K, SortedSet<V>> copyMap(
        Map<K, ? extends SortedSet<V>> map) {
    final ImmutableSortedMap.Builder<K, SortedSet<V>> b = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<K, ? extends SortedSet<V>> e : map.entrySet()) {
        b.put(e.getKey(), ImmutableSortedSet.copyOf(e.getValue()));
    }
    return b.build();
}
 
Example 14
Source File: F5BigipConfiguration.java    From batfish with Apache License 2.0 5 votes vote down vote up
private void initVirtualAddressRejectIcmpHeaders() {
  // incoming transformations
  ImmutableSortedMap.Builder<String, HeaderSpace> virtualAddressRejectIcmpHeaders =
      ImmutableSortedMap.naturalOrder();
  _virtualAddresses.forEach(
      (virtualAddressName, virtualAddress) ->
          computeVirtualAddressRejectIcmpHeaders(virtualAddress)
              .ifPresent(
                  matchedHeaders ->
                      virtualAddressRejectIcmpHeaders.put(virtualAddressName, matchedHeaders)));
  _virtualAddressRejectIcmpHeaders = virtualAddressRejectIcmpHeaders.build();
}
 
Example 15
Source File: NinjaBuild.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static void createDepsMap(
    RuleContext ruleContext,
    PathFragment workingDirectory,
    ImmutableSortedMap.Builder<PathFragment, Artifact> depsMapBuilder,
    ImmutableSortedMap.Builder<PathFragment, Artifact> symlinksMapBuilder)
    throws InterruptedException {
  FileProvider fileProvider =
      ruleContext.getPrerequisite("ninja_graph", TransitionMode.TARGET, FileProvider.class);
  Preconditions.checkNotNull(fileProvider);
  new NestedSetVisitor<Artifact>(
          a -> {
            symlinksMapBuilder.put(a.getExecPath().relativeTo(workingDirectory), a);
          },
          new VisitedState<>())
      .visit(fileProvider.getFilesToBuild());

  Map<String, TransitiveInfoCollection> mapping = ruleContext.getPrerequisiteMap("deps_mapping");
  for (Map.Entry<String, TransitiveInfoCollection> entry : mapping.entrySet()) {
    NestedSet<Artifact> filesToBuild =
        entry.getValue().getProvider(FileProvider.class).getFilesToBuild();
    if (!filesToBuild.isSingleton()) {
      ruleContext.attributeError(
          "deps_mapping",
          String.format(
              "'%s' contains more than one output. "
                  + "deps_mapping should only contain targets, producing a single output file.",
              entry.getValue().getLabel().getCanonicalForm()));
      return;
    }
    depsMapBuilder.put(PathFragment.create(entry.getKey()), filesToBuild.getSingleton());
  }
}
 
Example 16
Source File: CachingCalciteSchema.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected void addImplicitSubSchemaToBuilder(
    ImmutableSortedMap.Builder<String, CalciteSchema> builder) {
  ImmutableSortedMap<String, CalciteSchema> explicitSubSchemas = builder.build();
  final long now = System.currentTimeMillis();
  final SubSchemaCache subSchemaCache = implicitSubSchemaCache.get(now);
  for (String name : subSchemaCache.names.iterable()) {
    if (explicitSubSchemas.containsKey(name)) {
      // explicit sub-schema wins.
      continue;
    }
    builder.put(name, subSchemaCache.cache.getUnchecked(name));
  }
}
 
Example 17
Source File: StarlarkRepositoryContext.java    From bazel with Apache License 2.0 4 votes vote down vote up
private StarlarkExecutionResult executeRemote(
    Sequence<?> argumentsUnchecked, // <String> or <Label> expected
    int timeout,
    Map<String, String> environment,
    boolean quiet,
    String workingDirectory)
    throws EvalException, InterruptedException {
  Preconditions.checkState(canExecuteRemote());

  ImmutableSortedMap.Builder<PathFragment, Path> inputsBuilder =
      ImmutableSortedMap.naturalOrder();
  ImmutableList.Builder<String> argumentsBuilder = ImmutableList.builder();
  for (Object argumentUnchecked : argumentsUnchecked) {
    if (argumentUnchecked instanceof Label) {
      Label label = (Label) argumentUnchecked;
      Map.Entry<PathFragment, Path> remotePath = getRemotePathFromLabel(label);
      argumentsBuilder.add(remotePath.getKey().toString());
      inputsBuilder.put(remotePath);
    } else {
      argumentsBuilder.add(argumentUnchecked.toString());
    }
  }

  ImmutableList<String> arguments = argumentsBuilder.build();

  try (SilentCloseable c =
      Profiler.instance()
          .profile(ProfilerTask.STARLARK_REPOSITORY_FN, profileArgsDesc("remote", arguments))) {
    ExecutionResult result =
        remoteExecutor.execute(
            arguments,
            inputsBuilder.build(),
            getExecProperties(),
            ImmutableMap.copyOf(environment),
            workingDirectory,
            Duration.ofSeconds(timeout));

    String stdout = new String(result.stdout(), StandardCharsets.US_ASCII);
    String stderr = new String(result.stderr(), StandardCharsets.US_ASCII);

    if (!quiet) {
      OutErr outErr = OutErr.SYSTEM_OUT_ERR;
      outErr.printOut(stdout);
      outErr.printErr(stderr);
    }

    return new StarlarkExecutionResult(result.exitCode(), stdout, stderr);
  } catch (IOException e) {
    throw Starlark.errorf("remote_execute failed: %s", e.getMessage());
  }
}
 
Example 18
Source File: CalciteSchema.java    From Quicksql with MIT License 4 votes vote down vote up
/** Adds implicit table functions to a builder. */
protected abstract void addImplicitTablesBasedOnNullaryFunctionsToBuilder(
    ImmutableSortedMap.Builder<String, Table> builder);
 
Example 19
Source File: CiscoConversions.java    From batfish with Apache License 2.0 4 votes vote down vote up
/**
 * Converts a {@link CryptoMapEntry} to an {@link IpsecPhase2Policy} and a list of {@link
 * IpsecPeerConfig}
 */
private static void convertCryptoMapEntry(
    final Configuration c,
    CryptoMapEntry cryptoMapEntry,
    String cryptoMapNameSeqNumber,
    String cryptoMapName,
    Warnings w) {
  // skipping incomplete static or dynamic crypto maps
  if (!cryptoMapEntry.getDynamic()) {
    if (cryptoMapEntry.getAccessList() == null || cryptoMapEntry.getPeer() == null) {
      return;
    }
  } else {
    if (cryptoMapEntry.getAccessList() == null) {
      return;
    }
  }

  IpsecPhase2Policy ipsecPhase2Policy = toIpsecPhase2Policy(cryptoMapEntry);
  String ipsecPhase2PolicyName =
      String.format("~IPSEC_PHASE2_POLICY:%s~", cryptoMapNameSeqNumber);

  // add IPSec phase 2 policies to existing ones
  ImmutableSortedMap.Builder<String, IpsecPhase2Policy> ipsecPhase2PolicyBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPhase2Policies(
      ipsecPhase2PolicyBuilder
          .putAll(c.getIpsecPhase2Policies())
          .put(ipsecPhase2PolicyName, ipsecPhase2Policy)
          .build());

  ImmutableSortedMap.Builder<String, IpsecPeerConfig> ipsecPeerConfigsBuilder =
      ImmutableSortedMap.naturalOrder();
  c.setIpsecPeerConfigs(
      ipsecPeerConfigsBuilder
          .putAll(c.getIpsecPeerConfigs())
          .putAll(
              toIpsecPeerConfigs(
                  c,
                  cryptoMapEntry,
                  cryptoMapNameSeqNumber,
                  cryptoMapName,
                  ipsecPhase2PolicyName,
                  w))
          .build());
}
 
Example 20
Source File: TracerouteTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
private TableAnswerElement testDispositionMultipleRouters(String mask) throws IOException {
  NetworkFactory nf = new NetworkFactory();
  Configuration.Builder cb =
      nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS);

  ImmutableSortedMap.Builder<String, Configuration> configs =
      new ImmutableSortedMap.Builder<>(Comparator.naturalOrder());

  Configuration c1 = cb.build();
  configs.put(c1.getHostname(), c1);

  Vrf v1 = nf.vrfBuilder().setOwner(c1).build();

  Interface n1i0 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("1.0.0.1/" + mask))
          .setOwner(c1)
          .setVrf(v1)
          .setProxyArp(true)
          .build();

  v1.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(n1i0.getName())
              .setNetwork(Prefix.parse("1.0.0.0/25"))
              .setAdministrativeCost(1)
              .build()));

  Configuration c2 = cb.build();
  configs.put(c2.getHostname(), c2);

  Vrf v2 = nf.vrfBuilder().setOwner(c2).build();

  nf.interfaceBuilder()
      .setAddress(ConcreteInterfaceAddress.parse("1.0.0.2/" + mask))
      .setOwner(c2)
      .setVrf(v2)
      .setProxyArp(true)
      .build();

  Interface n2i1 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("2.0.0.1/24"))
          .setOwner(c2)
          .setVrf(v2)
          .setProxyArp(true)
          .build();

  v2.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(n2i1.getName())
              .setNetwork(Prefix.parse("1.0.0.0/25"))
              .setAdministrativeCost(1)
              .build()));

  Configuration c3 = cb.build();
  configs.put(c3.getHostname(), c3);

  Vrf v3 = nf.vrfBuilder().setOwner(c3).build();

  nf.interfaceBuilder()
      .setAddress(ConcreteInterfaceAddress.parse("2.0.0.2/24"))
      .setOwner(c3)
      .setVrf(v3)
      .setProxyArp(true)
      .build();

  Interface n3i1 =
      nf.interfaceBuilder()
          .setAddress(ConcreteInterfaceAddress.parse("1.0.0.3/24"))
          .setOwner(c3)
          .setVrf(v3)
          .setProxyArp(true)
          .build();

  v3.setStaticRoutes(
      ImmutableSortedSet.of(
          StaticRoute.builder()
              .setNextHopInterface(n3i1.getName())
              .setNetwork(Prefix.parse("1.0.0.0/25"))
              .setAdministrativeCost(1)
              .build()));

  Batfish batfish = BatfishTestUtils.getBatfish(configs.build(), _folder);
  batfish.computeDataPlane(batfish.getSnapshot());

  TracerouteQuestion question =
      new TracerouteQuestion(
          c1.getHostname(),
          PacketHeaderConstraints.builder().setDstIp("1.0.0.4").build(),
          false,
          DEFAULT_MAX_TRACES);

  TracerouteAnswerer answerer = new TracerouteAnswerer(question, batfish);
  TableAnswerElement answer = (TableAnswerElement) answerer.answer(batfish.getSnapshot());

  return answer;
}