com.google.common.collect.ImmutableSortedMap Java Examples

The following examples show how to use com.google.common.collect.ImmutableSortedMap. 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: PythonBinaryPackagable.java    From buck with 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 #2
Source File: ConfigCommand.java    From bazel with 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 #3
Source File: CachingCalciteSchema.java    From calcite with 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 #4
Source File: RoutesAnswererTest.java    From batfish with 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 #5
Source File: CxxSymlinkTreeHeaders.java    From buck with 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 #6
Source File: CxxFlags.java    From buck with 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 #7
Source File: Layer1NodeTest.java    From batfish with 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 #8
Source File: ScoreKBPAgainstERE.java    From tac-kbp-eal with 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 #9
Source File: TestFiltersAnswererTest.java    From batfish with 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 #10
Source File: DefinedStructuresAnswererTest.java    From batfish with 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 #11
Source File: ResourcesParametersTest.java    From buck with 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 #12
Source File: QuestionHelperTest.java    From batfish with 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 #13
Source File: RoleDimensionMappingTest.java    From batfish with 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 #14
Source File: FibImplTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNextHopInterfacesByRoute() throws IOException {
  String iface1 = "iface1";
  String iface2 = "iface2";
  String iface3 = "iface3";
  Ip ip1 = Ip.parse("1.1.1.0");
  Ip ip2 = Ip.parse("2.2.2.0");
  _ib.setName(iface1).setAddress(ConcreteInterfaceAddress.create(ip1, 24)).build();
  _ib.setName(iface2).setAddress(ConcreteInterfaceAddress.create(ip2, 24)).build();
  _ib.setName(iface3).setAddress(ConcreteInterfaceAddress.create(ip2, 24)).build();

  Batfish batfish =
      BatfishTestUtils.getBatfish(ImmutableSortedMap.of(_config.getHostname(), _config), folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  Fib fib =
      batfish
          .loadDataPlane(batfish.getSnapshot())
          .getFibs()
          .get(_config.getHostname())
          .get(Configuration.DEFAULT_VRF_NAME);

  // Should have one LocalRoute per interface (also one ConnectedRoute, but LocalRoute will have
  // longer prefix match). Should see only iface1 in interfaces to ip1.
  Set<FibEntry> nextHopsToIp1 = fib.get(ip1);
  assertThat(
      nextHopsToIp1, contains(hasAction(isFibForwardActionThat(hasInterfaceName(iface1)))));

  // Should see interfaces iface2 and iface3 in interfaces to ip2.
  Set<FibEntry> nextHopsIp2 = fib.get(ip2);
  assertThat(
      nextHopsIp2,
      containsInAnyOrder(
          ImmutableList.of(
              hasAction(isFibForwardActionThat(hasInterfaceName(iface2))),
              hasAction(isFibForwardActionThat(hasInterfaceName(iface3))))));
}
 
Example #15
Source File: SingularGuavaSortedMap2.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #16
Source File: OutputDirectories.java    From bazel with 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 #17
Source File: Node.java    From batfish with 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 #18
Source File: NinjaParserStepTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testNinjaRule() throws Exception {
  // Additionally test the situation when we get more line separators in the end.
  NinjaParserStep parser =
      createParser(
          "rule testRule  \n"
              + " command = executable --flag $TARGET $out && $POST_BUILD\n"
              + " description = Test rule for $TARGET\n"
              + " rspfile = $TARGET.in\n"
              + " deps = ${abc} $\n"
              + " ${cde}\n\n\n");
  NinjaRule ninjaRule = parser.parseNinjaRule();
  ImmutableSortedMap<NinjaRuleVariable, NinjaVariableValue> variables = ninjaRule.getVariables();
  assertThat(variables.keySet())
      .containsExactly(
          NinjaRuleVariable.COMMAND,
          NinjaRuleVariable.DESCRIPTION,
          NinjaRuleVariable.RSPFILE,
          NinjaRuleVariable.DEPS);
  assertThat(ninjaRule.getName()).isEqualTo("testRule");
  assertThat(variables.get(NinjaRuleVariable.DEPS).getRawText()).isEqualTo("${abc} $\n ${cde}");
  MockValueExpander expander = new MockValueExpander("###");
  assertThat(variables.get(NinjaRuleVariable.DEPS).getExpandedValue(expander))
      .isEqualTo("###abc $\n ###cde");
  assertThat(variables.get(NinjaRuleVariable.DESCRIPTION).getRawText())
      .isEqualTo("Test rule for ${TARGET}");
  assertThat(expander.getRequestedVariables()).containsExactly("abc", "cde");
}
 
Example #19
Source File: NinjaPhonyTargetsUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static void checkMapping(
    ImmutableSortedMap<PathFragment, PhonyTarget> pathsMap,
    String key,
    boolean isAlwaysDirty,
    String... values) {
  Set<PathFragment> expectedPaths =
      Arrays.stream(values).map(PathFragment::create).collect(Collectors.toSet());
  PhonyTarget phonyTarget = pathsMap.get(PathFragment.create(key));
  assertThat(phonyTarget).isNotNull();
  assertThat(phonyTarget.isAlwaysDirty()).isEqualTo(isAlwaysDirty);

  ImmutableSortedSet.Builder<PathFragment> paths = ImmutableSortedSet.naturalOrder();
  pathsMap.get(PathFragment.create(key)).visitExplicitInputs(pathsMap, paths::addAll);
  assertThat(paths.build()).containsExactlyElementsIn(expectedPaths);
}
 
Example #20
Source File: RegistryTest.java    From nomulus with 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 #21
Source File: PbrWithTracerouteTest.java    From batfish with 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 #22
Source File: JdbcEntryData.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public JdbcEntryData(Iterable<JdbcEntryDatum> jdbcEntryDatumEntries) {
  Preconditions.checkNotNull(jdbcEntryDatumEntries);
  ImmutableMap.Builder<String, JdbcEntryDatum> builder = ImmutableSortedMap.naturalOrder();
  for (JdbcEntryDatum datum : jdbcEntryDatumEntries) {
    builder.put(datum.getColumnName(), datum);
  }
  this.jdbcEntryData = builder.build();
}
 
Example #23
Source File: SimpleMetaCache.java    From LuckPerms with 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();
}
 
Example #24
Source File: AnnotatedIntervalCollectionUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void basicTest() throws IOException {
    final Set<String> headersOfInterest = Sets.newHashSet(Arrays.asList("name", "learning_SAMPLE_0"));
    final AnnotatedIntervalCollection simpleAnnotatedGenomicRegions =
            AnnotatedIntervalCollection.create(TEST_FILE.toPath(), headersOfInterest);

    Assert.assertEquals(simpleAnnotatedGenomicRegions.size(), 15);
    Assert.assertTrue(simpleAnnotatedGenomicRegions.getRecords().stream()
            .mapToInt(s -> s.getAnnotations().entrySet().size())
            .allMatch(i -> i == headersOfInterest.size()));
    Assert.assertTrue(simpleAnnotatedGenomicRegions.getRecords().stream().allMatch(s -> s.getAnnotations().keySet().containsAll(headersOfInterest)));

    // Grab the first 15 and test values
    List<AnnotatedInterval> gtRegions = Arrays.asList(
            new AnnotatedInterval(new SimpleInterval("1", 30365, 30503), ImmutableSortedMap.of("name", "target_1_None", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 69088, 70010), ImmutableSortedMap.of("name", "target_2_None", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 367656, 368599), ImmutableSortedMap.of("name", "target_3_None", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 621093, 622036), ImmutableSortedMap.of("name", "target_4_None", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 861319, 861395), ImmutableSortedMap.of("name", "target_5_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 865532, 865718), ImmutableSortedMap.of("name", "target_6_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 866416, 866471), ImmutableSortedMap.of("name", "target_7_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 871149, 871278), ImmutableSortedMap.of("name", "target_8_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 874417, 874511), ImmutableSortedMap.of("name", "target_9_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 874652, 874842), ImmutableSortedMap.of("name", "target_10_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 876521, 876688), ImmutableSortedMap.of("name", "target_11_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 877513, 877633), ImmutableSortedMap.of("name", "target_12_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 877787, 877870), ImmutableSortedMap.of("name", "target_13_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 877936, 878440), ImmutableSortedMap.of("name", "target_14_SAMD11", "learning_SAMPLE_0", "2")),
            new AnnotatedInterval(new SimpleInterval("1", 878630, 878759), ImmutableSortedMap.of("name", "target_15_SAMD11", "learning_SAMPLE_0", "2"))
    );

    Assert.assertEquals(simpleAnnotatedGenomicRegions.getRecords().subList(0, gtRegions.size()), gtRegions);
}
 
Example #25
Source File: HeaderSearchPaths.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Derives header search path attributes for the {@code targetNode}. */
HeaderSearchPathAttributes getHeaderSearchPathAttributes(
    TargetNode<? extends CxxLibraryDescription.CommonArg> targetNode) {
  ImmutableHeaderSearchPathAttributes.Builder builder =
      ImmutableHeaderSearchPathAttributes.builder().setTargetNode(targetNode);

  ImmutableSortedMap<Path, SourcePath> publicCxxHeaders = getPublicCxxHeaders(targetNode);
  builder.setPublicCxxHeaders(publicCxxHeaders);

  ImmutableSortedMap<Path, SourcePath> privateCxxHeaders = getPrivateCxxHeaders(targetNode);
  builder.setPrivateCxxHeaders(privateCxxHeaders);

  Set<Path> recursivePublicSystemIncludeDirectories =
      collectRecursivePublicSystemIncludeDirectories(targetNode);
  builder.setRecursivePublicSystemIncludeDirectories(recursivePublicSystemIncludeDirectories);

  Set<Path> recursivePublicIncludeDirectories =
      collectRecursivePublicIncludeDirectories(targetNode);
  builder.setRecursivePublicIncludeDirectories(recursivePublicIncludeDirectories);

  Set<Path> includeDirectories = extractIncludeDirectories(targetNode);
  builder.setIncludeDirectories(includeDirectories);

  ImmutableSet<Path> recursiveHeaderSearchPaths = collectRecursiveHeaderSearchPaths(targetNode);
  builder.setRecursiveHeaderSearchPaths(recursiveHeaderSearchPaths);

  ImmutableSet<Path> swiftIncludePaths = collectRecursiveSwiftIncludePaths(targetNode);
  builder.setSwiftIncludePaths(swiftIncludePaths);

  return builder.build();
}
 
Example #26
Source File: SqlTestFactory.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlTestFactory with(String name, Object value) {
  if (Objects.equals(value, options.get(name))) {
    return this;
  }
  ImmutableMap.Builder<String, Object> builder = ImmutableSortedMap.naturalOrder();
  // Protect from IllegalArgumentException: Multiple entries with same key
  for (Map.Entry<String, Object> entry : options.entrySet()) {
    if (name.equals(entry.getKey())) {
      continue;
    }
    builder.put(entry);
  }
  builder.put(name, value);
  return new SqlTestFactory(builder.build(), catalogReaderFactory, validatorFactory);
}
 
Example #27
Source File: CollectionUtil.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Sort map by value (lowest first) */
public static <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortMapByValueAscending(
		final Map<K, V> map) {
	final Ordering<K> valueThenKeyComparator = Ordering.natural()
			.onResultOf(Functions.forMap(map))
			.compound(Ordering.<K> natural());
	return ImmutableSortedMap.copyOf(map, valueThenKeyComparator);
}
 
Example #28
Source File: CumulusConversionsTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testComputeOspfProcess_HasArea() {
  CumulusNcluConfiguration ncluConfiguration = new CumulusNcluConfiguration();
  Interface vsIface = new Interface("iface", CumulusInterfaceType.PHYSICAL, null, null);
  vsIface.getOrCreateOspf().setOspfArea(1L);
  ncluConfiguration.getInterfaces().put("iface", vsIface);

  SortedMap<Long, OspfArea> areas =
      computeOspfAreas(ncluConfiguration, ImmutableList.of("iface"));
  assertThat(
      areas,
      equalTo(
          ImmutableSortedMap.of(
              1L, OspfArea.builder().addInterface("iface").setNumber(1L).build())));
}
 
Example #29
Source File: CompiledRoutes.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns compiled routes built from the given route map.
 *
 * @param metricRegistry the registry to generate per-(route,method) rate statistics in
 */
public CompiledRoutes(
    Map<RoutePath, Map<HttpMethod, Handler>> rawRoutes, MetricRegistry metricRegistry) {
  // Build a sorted map of the routes.
  ImmutableSortedMap.Builder<RoutePath, ImmutableMap<HttpMethod, Handler>> routesBuilder =
      ImmutableSortedMap.naturalOrder();
  for (Map.Entry<RoutePath, Map<HttpMethod, Handler>> routeEntry : rawRoutes.entrySet()) {
    ImmutableMap.Builder<HttpMethod, Handler> handlers = new ImmutableMap.Builder<>();
    RoutePath route = routeEntry.getKey();
    for (Map.Entry<HttpMethod, Handler> methodHandlerEntry : routeEntry.getValue().entrySet()) {
      HttpMethod method = methodHandlerEntry.getKey();

      // Wrap the user-provided handler in one that tracks request rates.
      String metricName = MetricRegistry.name("routes", method.name(), route.toString());
      String timerName = MetricRegistry.name("routeLatency", method.name(), route.toString());
      final Handler userHandler = methodHandlerEntry.getValue();
      final Meter meter = metricRegistry.meter(metricName);
      final Timer timer = metricRegistry.timer(timerName);

      // TODO (AD): Pull this out into an adapted handler in a separate class.
      Handler adaptedHandler =
          request -> {
            meter.mark();
            try {
              return timer.time(() -> userHandler.handle(request));
            } catch (Exception e) {
              return request.connectionContext().exceptionHandler().handle(request, e);
            }
          };
      handlers.put(method, adaptedHandler);
    }

    routesBuilder.put(route, handlers.build());
  }

  this.routes = routesBuilder.build();
}
 
Example #30
Source File: CommandTool.java    From buck with Apache License 2.0 5 votes vote down vote up
private CommandTool(
    Optional<Tool> baseTool,
    ImmutableList<Arg> args,
    ImmutableSortedMap<String, Arg> environment,
    ImmutableSortedSet<SourcePath> extraInputs,
    ImmutableSortedSet<NonHashableSourcePathContainer> nonHashableInputs) {
  this.baseTool = baseTool;
  this.args = args;
  this.environment = environment;
  this.extraInputs = extraInputs;
  this.nonHashableInputs = nonHashableInputs;
}