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

The following examples show how to use com.google.common.collect.ImmutableSortedMap. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: buck   Source File: CxxSymlinkTreeHeaders.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <E extends Exception> void serialize(
    CxxSymlinkTreeHeaders instance, ValueVisitor<E> serializer) throws E {
  INCLUDE_TYPE_TYPE_INFO.visit(instance.getIncludeType(), serializer);
  HEADER_MAP_TYPE_INFO.visit(instance.getHeaderMap(), serializer);
  serializer.visitSourcePath(instance.getRoot());
  INCLUDE_ROOT_TYPE_INFO.visit(instance.getIncludeRoot(), serializer);
  ImmutableSortedMap<Path, SourcePath> nameToPathMap = instance.getNameToPathMap();
  serializer.visitInteger(nameToPathMap.size());
  serializer.visitString(instance.getSymlinkTreeClass());
  RichStream.from(nameToPathMap.entrySet())
      .forEachThrowing(
          entry -> {
            Preconditions.checkState(!entry.getKey().isAbsolute());
            serializer.visitString(entry.getKey().toString());
            serializer.visitSourcePath(entry.getValue());
          });
}
 
Example 2
Source Project: batfish   Source File: Layer1NodeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testToLogicalNodeNonAggregate() {
  String c1Name = "c1";
  String iName = "i1";

  Configuration c1 = _cb.setHostname(c1Name).build();
  Vrf v1 = _vb.setOwner(c1).build();
  _ib.setOwner(c1).setVrf(v1);
  _ib.setName(iName).build();

  NetworkConfigurations networkConfigurations =
      NetworkConfigurations.of(ImmutableSortedMap.of(c1Name, c1));
  Layer1Node node = new Layer1Node(c1Name, iName);

  // If node is not member of an aggregate, the resulting logical node should reference the
  // physical interface name.
  assertThat(node.toLogicalNode(networkConfigurations), equalTo(node));
}
 
Example 3
Source Project: batfish   Source File: TestFiltersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOneRowPerFilterPerConfig() {
  IpAccessList.Builder aclb = _nf.aclBuilder();
  Configuration c1 = _cb.build();
  Configuration c2 = _cb.build();
  Configuration c3 = _cb.build();

  // Create 2 ACLs for each of 3 configs.
  aclb.setOwner(c1).build();
  aclb.build();
  aclb.setOwner(c2).build();
  aclb.build();
  aclb.setOwner(c3).build();
  aclb.build();

  IBatfish batfish =
      new MockBatfish(
          ImmutableSortedMap.of(
              c1.getHostname(), c1, c2.getHostname(), c2, c3.getHostname(), c3));
  TestFiltersQuestion question = new TestFiltersQuestion(null, null, null, null);
  TestFiltersAnswerer answerer = new TestFiltersAnswerer(question, batfish);
  TableAnswerElement answer = answerer.answer(batfish.getSnapshot());

  // There should be 6 rows
  assertThat(answer.getRows(), hasSize(6));
}
 
Example 4
Source Project: buck   Source File: PythonBinaryPackagable.java    License: Apache License 2.0 6 votes vote down vote up
@Value.Lazy
public Optional<PythonMappedComponents> getPythonSources() {
  return getPythonModules()
      .<Optional<PythonMappedComponents>>map(
          components ->
              components.getComponents().isEmpty()
                  ? Optional.empty()
                  : Optional.of(
                      PythonMappedComponents.of(
                          ImmutableSortedMap.copyOf(
                              Maps.filterKeys(
                                  components.getComponents(),
                                  dst ->
                                      MorePaths.getFileExtension(dst)
                                          .equals(PythonUtil.SOURCE_EXT))))))
      .orElseGet(Optional::empty);
}
 
Example 5
Source Project: tac-kbp-eal   Source File: ScoreKBPAgainstERE.java    License: MIT License 6 votes vote down vote up
@Inject
ScoreKBPAgainstERE(
    final Parameters params,
    final Map<String, ScoringEventObserver<DocLevelEventArg, DocLevelEventArg>> scoringEventObservers,
    final Map<String, Inspector<EvalPair<ResponsesAndLinking, ResponsesAndLinking>>> responseAndLinkingObservers,
    final ResponsesAndLinkingFromEREExtractor responsesAndLinkingFromEREExtractor,
    ResponsesAndLinkingFromKBPExtractorFactory responsesAndLinkingFromKBPExtractorFactory,
    @DocIDsToScoreP Set<Symbol> docIdsToScore,
    EREDocumentSource ereDocumentSource,
    Predicate<DocLevelEventArg> inScopePredicate) {
  this.params = checkNotNull(params);
  // we use a sorted map because the binding of plugins may be non-deterministic
  this.scoringEventObservers = ImmutableSortedMap.copyOf(scoringEventObservers);
  this.responseAndLinkingObservers = ImmutableSortedMap.copyOf(responseAndLinkingObservers);
  this.responsesAndLinkingFromEREExtractor = checkNotNull(responsesAndLinkingFromEREExtractor);
  this.responsesAndLinkingFromKBPExtractorFactory = responsesAndLinkingFromKBPExtractorFactory;
  this.docIdsToScore = ImmutableSet.copyOf(docIdsToScore);
  this.ereDocumentSource = ereDocumentSource;
  this.inScopePredicate = inScopePredicate;
}
 
Example 6
Source Project: calcite   Source File: CachingCalciteSchema.java    License: Apache License 2.0 6 votes vote down vote up
protected void addImplicitTablesBasedOnNullaryFunctionsToBuilder(
    ImmutableSortedMap.Builder<String, Table> builder) {
  ImmutableSortedMap<String, Table> explicitTables = builder.build();

  final long now = System.currentTimeMillis();
  final NameSet set = implicitFunctionCache.get(now);
  for (String s : set.iterable()) {
    // explicit table wins.
    if (explicitTables.containsKey(s)) {
      continue;
    }
    for (Function function : schema.getFunctions(s)) {
      if (function instanceof TableMacro
          && function.getParameters().isEmpty()) {
        final Table table = ((TableMacro) function).apply(ImmutableList.of());
        builder.put(s, table);
      }
    }
  }
}
 
Example 7
Source Project: bazel   Source File: ConfigCommand.java    License: Apache License 2.0 6 votes vote down vote up
private static ConfigurationDiffForOutput getConfigurationDiffForOutput(
    String configHash1,
    String configHash2,
    Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>> diffs) {
  ImmutableSortedSet.Builder<FragmentDiffForOutput> fragmentDiffs =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  diffs.rowKeySet().stream()
      .forEach(
          fragmentClass -> {
            String fragmentName =
                fragmentClass.equals(UserDefinedFragment.class)
                    ? UserDefinedFragment.DESCRIPTIVE_NAME
                    : fragmentClass.getName();
            ImmutableSortedMap<String, Pair<String, String>> sortedOptionDiffs =
                diffs.row(fragmentClass).entrySet().stream()
                    .collect(
                        toImmutableSortedMap(
                            Ordering.natural(),
                            Map.Entry::getKey,
                            e -> toNullableStringPair(e.getValue())));
            fragmentDiffs.add(new FragmentDiffForOutput(fragmentName, sortedOptionDiffs));
          });
  return new ConfigurationDiffForOutput(
      configHash1, configHash2, ImmutableList.copyOf(fragmentDiffs.build()));
}
 
Example 8
Source Project: batfish   Source File: RoutesAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHasNodeFiltering() {
  SortedMap<String, SortedMap<String, GenericRib<AbstractRouteDecorator>>> ribs =
      ImmutableSortedMap.of(
          "n1",
          ImmutableSortedMap.of(
              Configuration.DEFAULT_VRF_NAME,
              new MockRib<>(
                  ImmutableSet.of(
                      StaticRoute.builder()
                          .setAdministrativeCost(1)
                          .setNetwork(Prefix.parse("1.1.1.0/24"))
                          .setNextHopInterface("Null")
                          .build()))));

  Multiset<Row> actual =
      getMainRibRoutes(
          ribs,
          ImmutableSet.of("differentNode"),
          null,
          RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER,
          ".*",
          null);

  assertThat(actual, hasSize(0));
}
 
Example 9
Source Project: batfish   Source File: DefinedStructuresAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SpecifierContext specifierContext(NetworkSnapshot snapshot) {
  assertThat(snapshot, equalTo(getSnapshot()));
  Configuration c1 = new Configuration("a", ConfigurationFormat.CISCO_IOS);
  Configuration c2 = new Configuration("b", ConfigurationFormat.CISCO_IOS);
  Configuration c3 = new Configuration("c", ConfigurationFormat.CISCO_IOS);
  Configuration c4 = new Configuration("d", ConfigurationFormat.CISCO_IOS);
  return MockSpecifierContext.builder()
      .setConfigs(
          ImmutableSortedMap.of(
              c1.getHostname(),
              c1,
              c2.getHostname(),
              c2,
              c3.getHostname(),
              c3,
              c4.getHostname(),
              c4))
      .build();
}
 
Example 10
Source Project: buck   Source File: CxxFlags.java    License: Apache License 2.0 6 votes vote down vote up
/** Expand flag macros in all CxxPlatform StringArg flags. */
public static void translateCxxPlatformFlags(
    CxxPlatform.Builder cxxPlatformBuilder,
    CxxPlatform cxxPlatform,
    ImmutableMap<String, Arg> flagMacros) {
  Function<Arg, Arg> translateFunction =
      new CxxFlags.TranslateMacrosArgsFunction(ImmutableSortedMap.copyOf(flagMacros));
  Function<ImmutableList<Arg>, ImmutableList<Arg>> expandMacros =
      flags -> flags.stream().map(translateFunction).collect(ImmutableList.toImmutableList());
  cxxPlatformBuilder.setAsflags(expandMacros.apply(cxxPlatform.getAsflags()));
  cxxPlatformBuilder.setAsppflags(expandMacros.apply(cxxPlatform.getAsppflags()));
  cxxPlatformBuilder.setCflags(expandMacros.apply(cxxPlatform.getCflags()));
  cxxPlatformBuilder.setCxxflags(expandMacros.apply(cxxPlatform.getCxxflags()));
  cxxPlatformBuilder.setCppflags(expandMacros.apply(cxxPlatform.getCppflags()));
  cxxPlatformBuilder.setCxxppflags(expandMacros.apply(cxxPlatform.getCxxppflags()));
  cxxPlatformBuilder.setCudappflags(expandMacros.apply(cxxPlatform.getCudappflags()));
  cxxPlatformBuilder.setCudaflags(expandMacros.apply(cxxPlatform.getCudaflags()));
  cxxPlatformBuilder.setHipppflags(expandMacros.apply(cxxPlatform.getHipppflags()));
  cxxPlatformBuilder.setHipflags(expandMacros.apply(cxxPlatform.getHipflags()));
  cxxPlatformBuilder.setAsmppflags(expandMacros.apply(cxxPlatform.getAsmppflags()));
  cxxPlatformBuilder.setAsmflags(expandMacros.apply(cxxPlatform.getAsmflags()));
  cxxPlatformBuilder.setLdflags(expandMacros.apply(cxxPlatform.getLdflags()));
  cxxPlatformBuilder.setStripFlags(expandMacros.apply(cxxPlatform.getStripFlags()));
  cxxPlatformBuilder.setArflags(expandMacros.apply(cxxPlatform.getArflags()));
  cxxPlatformBuilder.setRanlibflags(expandMacros.apply(cxxPlatform.getRanlibflags()));
}
 
Example 11
Source Project: bazel   Source File: ClassCache.java    License: Apache License 2.0 5 votes vote down vote up
/** Second argument in the Map is if the jar is used directly (at least once). */
public ImmutableMap<Path, Boolean> collectUsedJarFiles() {
  Map<Path, Boolean> usedJars = new HashMap<>();
  for (Map.Entry<String, LazyClassEntry> entry : classIndex.entrySet()) {
    LazyClassEntry clazz = entry.getValue();
    if (clazz.isResolved()) {
      if (!usedJars.containsKey(clazz.jarPath) || clazz.state.direct()) {
        usedJars.put(clazz.jarPath, clazz.state.direct());
      }
    }
  }
  return ImmutableSortedMap.copyOf(usedJars);
}
 
Example 12
Source Project: buck   Source File: AppleDescriptions.java    License: Apache License 2.0 5 votes vote down vote up
public static ImmutableSortedMap<String, SourcePath> convertAppleHeadersToPublicCxxHeaders(
    BuildTarget buildTarget,
    Function<SourcePath, Path> pathResolver,
    Path headerPathPrefix,
    CxxLibraryDescription.CommonArg arg) {
  // The exported headers in the populated cxx constructor arg will contain exported headers from
  // the apple constructor arg with the public include style.
  return AppleDescriptions.parseAppleHeadersForUseFromOtherTargets(
      buildTarget, pathResolver, headerPathPrefix, arg.getExportedHeaders());
}
 
Example 13
Source Project: batfish   Source File: Node.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new node based on the configuration. Initializes virtual routers based on {@link
 * Configuration} VRFs.
 *
 * @param configuration the {@link Configuration} backing this node
 */
public Node(@Nonnull Configuration configuration) {
  _c = configuration;
  ImmutableSortedMap.Builder<String, VirtualRouter> b = ImmutableSortedMap.naturalOrder();
  for (String vrfName : _c.getVrfs().keySet()) {
    VirtualRouter vr = new VirtualRouter(vrfName, this);
    b.put(vrfName, vr);
  }
  _virtualRouters = b.build();
}
 
Example 14
Source Project: phoenix-tephra   Source File: TransactionProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() throws Exception {
  Configuration hConf = new Configuration();
  String rootDir = tmpFolder.newFolder().getAbsolutePath();
  hConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, rootDir);
  hConf.set(HConstants.HBASE_DIR, rootDir + "/hbase");

  dfsCluster = new MiniDFSCluster.Builder(hConf).numDataNodes(1).build();
  dfsCluster.waitActive();
  conf = HBaseConfiguration.create(dfsCluster.getFileSystem().getConf());

  conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER);
  conf.unset(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES);
  String localTestDir = tmpFolder.newFolder().getAbsolutePath();
  conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, localTestDir);
  conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, DefaultSnapshotCodec.class.getName());

  // write an initial transaction snapshot
  InvalidTxList invalidTxList = new InvalidTxList();
  invalidTxList.addAll(invalidSet);
  TransactionSnapshot txSnapshot = TransactionSnapshot.copyFrom(
      System.currentTimeMillis(), V[6] - 1, V[7], invalidTxList,
      // this will set visibility upper bound to V[6]
      Maps.newTreeMap(ImmutableSortedMap.of(V[6], new TransactionManager.InProgressTx(
        V[6] - 1, Long.MAX_VALUE, TransactionManager.InProgressType.SHORT))),
      new HashMap<Long, TransactionManager.ChangeSet>(), new TreeMap<Long, TransactionManager.ChangeSet>());
  txVisibilityState = new TransactionSnapshot(txSnapshot.getTimestamp(), txSnapshot.getReadPointer(),
                                              txSnapshot.getWritePointer(), txSnapshot.getInvalid(),
                                              txSnapshot.getInProgress());
  HDFSTransactionStateStorage tmpStorage =
    new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf), new TxMetricsCollector());
  tmpStorage.startAndWait();
  tmpStorage.writeSnapshot(txSnapshot);
  tmpStorage.stopAndWait();
  long globalMemStoreLimit = (long) (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
          .getMax() * MemorySizeUtil.getGlobalMemStoreHeapPercent(conf, false));
  chunkCreator = ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false,
          globalMemStoreLimit, 0.2f, MemStoreLAB.POOL_INITIAL_SIZE_DEFAULT, null);
  assertTrue(chunkCreator != null);
}
 
Example 15
Source Project: james-project   Source File: MailboxListenerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void addedShouldNotBeNoopWhenNotEmpty() {
    MailboxListener.Added added = new MailboxListener.Added(SESSION_ID, BOB, PATH, MAILBOX_ID, ImmutableSortedMap.of(UID, META_DATA),
        Event.EventId.random());

    assertThat(added.isNoop()).isFalse();
}
 
Example 16
Source Project: buck   Source File: RustCompileRule.java    License: Apache License 2.0 5 votes vote down vote up
public static RustCompileRule from(
    SourcePathRuleFinder ruleFinder,
    BuildTarget buildTarget,
    ProjectFilesystem projectFilesystem,
    String filename,
    Tool compiler,
    Linker linker,
    ImmutableList<Arg> args,
    ImmutableList<Arg> depArgs,
    ImmutableList<Arg> linkerArgs,
    ImmutableSortedMap<String, Arg> environment,
    ImmutableSortedMap<SourcePath, Optional<String>> mappedSources,
    String rootModule,
    RemapSrcPaths remapSrcPaths,
    Optional<String> xcrunSdkPath) {
  return new RustCompileRule(
      buildTarget,
      projectFilesystem,
      ruleFinder,
      filename,
      compiler,
      linker,
      args,
      depArgs,
      linkerArgs,
      environment,
      mappedSources,
      rootModule,
      remapSrcPaths,
      xcrunSdkPath);
}
 
Example 17
Source Project: batfish   Source File: UniqueIpAssignmentsQuestionPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private SortedMap<Ip, SortedSet<NodeInterfacePair>> getDuplicateIps(NetworkSnapshot snapshot) {
  UniqueIpAssignmentsQuestion question = (UniqueIpAssignmentsQuestion) _question;
  SpecifierContext ctxt = _batfish.specifierContext(snapshot);
  Map<String, Configuration> configs = ctxt.getConfigs();
  Set<String> nodes = question.getNodeSpecifier().resolve(ctxt);
  // we do nodes and interfaces separately because of interface equality is currently broken
  // (does not take owner node into account)
  return nodes.stream()
      .flatMap(n -> question.getInterfaceSpecifier().resolve(ImmutableSet.of(n), ctxt).stream())
      .map(
          ifaceId ->
              configs.get(ifaceId.getHostname()).getAllInterfaces().get(ifaceId.getInterface()))
      // narrow to interfaces of interest
      .filter(iface -> (!question.getEnabledIpsOnly() || iface.getActive()))
      // convert to stream of Entry<Ip, NodeInterfacePair>
      .flatMap(
          iface ->
              iface.getAllConcreteAddresses().stream()
                  .map(
                      ifaceAdrr ->
                          Maps.immutableEntry(ifaceAdrr.getIp(), NodeInterfacePair.of(iface))))
      // group by Ip
      .collect(Multimaps.toMultimap(Entry::getKey, Entry::getValue, TreeMultimap::create))
      // convert to stream of Entry<Ip, Set<NodeInterfacePair>>
      .asMap()
      .entrySet()
      .stream()
      // narrow to entries with multiple NodeInterfacePairs
      .filter(entry -> entry.getValue().size() > 1)
      .collect(
          ImmutableSortedMap.toImmutableSortedMap(
              Comparator.naturalOrder(),
              Entry::getKey,
              entry -> ImmutableSortedSet.copyOf(entry.getValue())));
}
 
Example 18
Source Project: buck   Source File: ExopackageInstallerIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void setDefaultFullBuildState() {
  currentBuildState =
      new ExoState(
          "apk-content\n",
          createFakeManifest("manifest-content\n"),
          ImmutableList.of("secondary-dex0\n", "secondary-dex1\n"),
          ImmutableSortedMap.of(
              "libs/" + SdkConstants.ABI_INTEL_ATOM + "/libone.so", "x86-libone\n",
              "libs/" + SdkConstants.ABI_INTEL_ATOM + "/libtwo.so", "x86-libtwo\n",
              "libs/" + SdkConstants.ABI_ARMEABI_V7A + "/libone.so", "armv7-libone\n",
              "libs/" + SdkConstants.ABI_ARMEABI_V7A + "/libtwo.so", "armv7-libtwo\n"),
          ImmutableList.of("exo-resources.apk\n", "exo-assets0\n", "exo-assets1\n"),
          ImmutableList.of("module_1\n", "module_2\n"));
}
 
Example 19
Source Project: nomulus   Source File: AllocationTokenTest.java    License: Apache License 2.0 5 votes vote down vote up
private void assertBadTransition(
    ImmutableSortedMap<DateTime, TokenStatus> map, TokenStatus from, TokenStatus to) {
  IllegalArgumentException thrown =
      assertThrows(
          IllegalArgumentException.class,
          () -> new AllocationToken.Builder().setTokenStatusTransitions(map));
  assertThat(thrown)
      .hasMessageThat()
      .isEqualTo(
          String.format("tokenStatusTransitions map cannot transition from %s to %s.", from, to));
}
 
Example 20
Source Project: bazel   Source File: ConfigCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link FragmentOptions}'s native option settings in canonical order.
 *
 * <p>While actual option values are objects, we serialize them to strings to prevent command
 * output from interpreting them more deeply than we want for simple "name=value" output.
 */
private static ImmutableSortedMap<String, String> getOrderedNativeOptions(
    FragmentOptions options) {
  return options.asMap().entrySet().stream()
      // While technically part of CoreOptions, --define is practically a user-definable flag so
      // we include it in the user-defined fragment for clarity. See getOrderedUserDefinedOptions.
      .filter(
          entry ->
              !(options.getClass().equals(CoreOptions.class) && entry.getKey().equals("define")))
      .collect(
          toImmutableSortedMap(
              Ordering.natural(), e -> e.getKey(), e -> String.valueOf(e.getValue())));
}
 
Example 21
Source Project: james-project   Source File: EventFactory.java    License: Apache License 2.0 5 votes vote down vote up
ExpungedFinalStage(Event.EventId eventId, MailboxPath path, MailboxId mailboxId, Username username, MailboxSession.SessionId sessionId, Map<MessageUid, MessageMetaData> metaData) {
    this.eventId = eventId;
    this.path = path;
    this.mailboxId = mailboxId;
    this.username = username;
    this.sessionId = sessionId;
    this.metaData = ImmutableSortedMap.copyOf(metaData);
}
 
Example 22
Source Project: buck   Source File: ProgressEstimatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdatesStorageWithProjectGenerationEstimationsAfterCommandInvocation()
    throws IOException {
  Path storagePath = getStorageForTest();

  Map<String, Object> storageContents =
      ImmutableSortedMap.<String, Object>naturalOrder()
          .put(
              "project arg1 arg2",
              ImmutableSortedMap.<String, Number>naturalOrder()
                  .put(ProgressEstimator.EXPECTED_NUMBER_OF_GENERATED_PROJECT_FILES, 10)
                  .build())
          .build();
  String contents = ObjectMappers.WRITER.writeValueAsString(storageContents);
  Files.write(storagePath, contents.getBytes(StandardCharsets.UTF_8));

  // path is 2 levels up folder
  ProgressEstimator estimator =
      new ProgressEstimator(Optional.of(storagePath), getBuckEventBus());

  estimator.setCurrentCommand("project", ImmutableList.of("arg1", "arg2"));
  estimator.didGenerateProjectForTarget();
  estimator.didGenerateProjectForTarget();
  estimator.didGenerateProjectForTarget();
  estimator.didFinishProjectGeneration();

  estimator.close();

  Map<String, Map<String, Number>> jsonObject =
      ObjectMappers.READER.readValue(
          ObjectMappers.createParser(Files.readAllBytes(storagePath)),
          new TypeReference<HashMap<String, Map<String, Number>>>() {});

  Map<String, Number> storedValues = jsonObject.get("project arg1 arg2");
  assertThat(
      storedValues.get(ProgressEstimator.EXPECTED_NUMBER_OF_GENERATED_PROJECT_FILES).intValue(),
      Matchers.equalTo(3));
}
 
Example 23
Source Project: bazel   Source File: OutputDirectories.java    License: Apache License 2.0 5 votes vote down vote up
private String buildMnemonic(
    CoreOptions options, ImmutableSortedMap<Class<? extends Fragment>, Fragment> fragments) {
  // See explanation at declaration for outputRoots.
  String platformSuffix = (options.platformSuffix != null) ? options.platformSuffix : "";
  ArrayList<String> nameParts = new ArrayList<>();
  for (Fragment fragment : fragments.values()) {
    nameParts.add(fragment.getOutputDirectoryName());
  }
  nameParts.add(options.compilationMode + platformSuffix);
  if (options.transitionDirectoryNameFragment != null) {
    nameParts.add(options.transitionDirectoryNameFragment);
  }
  return Joiner.on('-').skipNulls().join(nameParts);
}
 
Example 24
Source Project: buck   Source File: ResourcesParametersTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void canGetOutputNameFromHasOutputName() {
  BuildTarget buildTarget = BuildTargetFactory.newInstance("//android/java:resources");
  OutputLabel outputLabel = OutputLabel.of("label");
  FakeBuildRuleWithOutputName rule =
      new FakeBuildRuleWithOutputName(
          buildTarget,
          ImmutableMap.of(outputLabel, "label", OutputLabel.defaultLabel(), "default"));
  SourcePathRuleFinder ruleFinder =
      new FakeActionGraphBuilder(ImmutableMap.of(buildTarget, rule));
  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();

  SourcePath pathWithDefaultOutputLabel =
      ExplicitBuildTargetSourcePath.of(buildTarget, Paths.get("default"));
  SourcePath pathWithNamedOutputLabel =
      ExplicitBuildTargetSourcePath.of(
          BuildTargetWithOutputs.of(buildTarget, outputLabel),
          Paths.get("explicit_path_with_label"));

  ImmutableSortedMap<String, SourcePath> actual =
      ResourcesParameters.getNamedResources(
          ruleFinder,
          projectFilesystem,
          ImmutableSortedSet.of(pathWithDefaultOutputLabel, pathWithNamedOutputLabel));
  assertEquals(
      ImmutableSortedMap.of(
              PathFormatter.pathWithUnixSeparators(
                      getBasePath(buildTarget, projectFilesystem.getFileSystem())
                          .resolve("default")),
                  pathWithDefaultOutputLabel,
              PathFormatter.pathWithUnixSeparators(
                      getBasePath(buildTarget, projectFilesystem.getFileSystem())
                          .resolve("label")),
                  pathWithNamedOutputLabel)
          .entrySet(),
      actual.entrySet());
}
 
Example 25
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public SingularGuavaSortedMap2<A, B> build() {
  com.google.common.collect.ImmutableSortedMap<java.lang.Object, java.lang.Object> rawTypes = this.rawTypes == null ? com.google.common.collect.ImmutableSortedMap.<java.lang.Object, java.lang.Object>of() : this.rawTypes.build();
  com.google.common.collect.ImmutableSortedMap<Integer, Float> integers = this.integers == null ? com.google.common.collect.ImmutableSortedMap.<Integer, Float>of() : this.integers.build();
  com.google.common.collect.ImmutableSortedMap<A, B> generics = this.generics == null ? com.google.common.collect.ImmutableSortedMap.<A, B>of() : this.generics.build();
  com.google.common.collect.ImmutableSortedMap<Number, String> extendsGenerics = this.extendsGenerics == null ? com.google.common.collect.ImmutableSortedMap.<Number, String>of() : this.extendsGenerics.build();
  return new SingularGuavaSortedMap2<A, B>(rawTypes, integers, generics, extendsGenerics);
}
 
Example 26
Source Project: batfish   Source File: RoleDimensionMappingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGroups() {
  RoleDimensionMapping rdMap =
      new RoleDimensionMapping("x(b.*d)(.+)y.*", ImmutableList.of(2, 1), null);
  Set<String> nodes = ImmutableSet.of("xbordery", "core", "xbordery2", "xcorey");
  SortedMap<String, String> nodeRolesMap = rdMap.createNodeRolesMap(nodes);
  assertThat(
      nodeRolesMap,
      equalTo(ImmutableSortedMap.of("xbordery", "er-bord", "xbordery2", "er-bord")));
}
 
Example 27
Source Project: batfish   Source File: QuestionHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateTemplateExtraParameter() throws JSONException, IOException {
  JSONObject template =
      new JSONObject(readResource("org/batfish/client/extraParameter.json", UTF_8));

  _thrown.expect(BatfishException.class);
  _thrown.expectMessage("Unrecognized field");

  QuestionHelper.validateTemplate(
      template,
      ImmutableSortedMap.of("parameter1", new IntNode(2), "parameter2", new IntNode(2)));
}
 
Example 28
Source Project: nomulus   Source File: RegistryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPdtLooksLikeGa() {
  Registry registry =
      Registry.get("tld")
          .asBuilder()
          .setTldStateTransitions(ImmutableSortedMap.of(START_OF_TIME, TldState.PDT))
          .build();
  assertThat(registry.getTldState(START_OF_TIME)).isEqualTo(GENERAL_AVAILABILITY);
}
 
Example 29
Source Project: batfish   Source File: PbrWithTracerouteTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOverrideIpExitsNetwork() throws IOException {

  NetworkFactory nf = new NetworkFactory();
  Configuration c = buildPBRConfig(nf);

  Batfish batfish = getBatfish(ImmutableSortedMap.of(c.getHostname(), c), _folder);
  NetworkSnapshot snapshot = batfish.getSnapshot();
  batfish.computeDataPlane(snapshot);

  Ip dstIp = Ip.parse("1.1.1.250");
  Flow flow =
      Flow.builder()
          .setIngressNode(c.getHostname())
          .setIngressInterface(_ingressIfaceName)
          .setDstIp(dstIp)
          .setSrcIp(Ip.ZERO)
          .build();
  SortedMap<Flow, List<Trace>> traces =
      batfish.getTracerouteEngine(snapshot).computeTraces(ImmutableSet.of(flow), false);
  assertThat(
      traces.get(flow),
      contains(
          allOf(
              hasDisposition(FlowDisposition.DELIVERED_TO_SUBNET),
              hasLastHop(
                  hasOutputInterface(NodeInterfacePair.of(c.getHostname(), _pbrOutIface))))));
}
 
Example 30
Source Project: LuckPerms   Source File: SimpleMetaCache.java    License: MIT License 5 votes vote down vote up
public void loadMeta(MetaAccumulator meta) {
    this.meta = Multimaps.asMap(ImmutableListMultimap.copyOf(meta.getMeta()));

    MetaValueSelector metaValueSelector = this.queryOptions.option(MetaValueSelector.KEY)
            .orElseGet(() -> this.plugin.getConfiguration().get(ConfigKeys.META_VALUE_SELECTOR));

    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    for (Map.Entry<String, List<String>> e : this.meta.entrySet()) {
        if (e.getValue().isEmpty()) {
            continue;
        }

        String selected = metaValueSelector.selectValue(e.getKey(), e.getValue());
        if (selected == null) {
            throw new NullPointerException(metaValueSelector + " returned null");
        }

        builder.put(e.getKey(), selected);
    }
    this.flattenedMeta = builder.build();

    this.prefixes = ImmutableSortedMap.copyOfSorted(meta.getPrefixes());
    this.suffixes = ImmutableSortedMap.copyOfSorted(meta.getSuffixes());
    this.weight = meta.getWeight();
    this.primaryGroup = meta.getPrimaryGroup();
    this.prefixDefinition = meta.getPrefixDefinition();
    this.suffixDefinition = meta.getSuffixDefinition();
    this.prefix = meta.getPrefix();
    this.suffix = meta.getSuffix();
}