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

The following examples show how to use com.google.common.collect.ImmutableMultiset. 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: presto   Source File: QueryAssertions.java    License: Apache License 2.0 6 votes vote down vote up
public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message)
{
    assertNotNull(actual, "actual is null");
    assertNotNull(expected, "expected is null");

    ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
    ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
    if (!actualSet.equals(expectedSet)) {
        Multiset<?> unexpectedRows = Multisets.difference(actualSet, expectedSet);
        Multiset<?> missingRows = Multisets.difference(expectedSet, actualSet);
        int limit = 100;
        fail(format(
                "%snot equal\n" +
                        "Actual rows (up to %s of %s extra rows shown, %s rows in total):\n    %s\n" +
                        "Expected rows (up to %s of %s missing rows shown, %s rows in total):\n    %s\n",
                message == null ? "" : (message + "\n"),
                limit,
                unexpectedRows.size(),
                actualSet.size(),
                Joiner.on("\n    ").join(Iterables.limit(unexpectedRows, limit)),
                limit,
                missingRows.size(),
                expectedSet.size(),
                Joiner.on("\n    ").join(Iterables.limit(missingRows, limit))));
    }
}
 
Example 2
Source Project: batfish   Source File: SpecifiersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolveInterfaceTest() {
  SpecifiersQuestion question = new SpecifiersQuestion(QueryType.INTERFACE);
  question.setInterfaceSpecifierInput(_iface1.getName());

  // only iface1 should be present (with a node specifier all nodes are included)
  assertThat(
      resolveInterface(question, _context).getRows().getData(),
      equalTo(
          ImmutableMultiset.of(
              Row.of(
                  COL_INTERFACE, NodeInterfacePair.of(_c1.getHostname(), _iface1.getName())))));

  // nothing should match since the node specifier does not match anything
  question.setNodeSpecifierInput("foofoo");
  assertThat(
      resolveInterface(question, _context).getRows().getData(), equalTo(ImmutableMultiset.of()));
}
 
Example 3
Source Project: guava-beta-checker   Source File: TestCompiler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the given diagnostics contain errors with a message containing "[CheckerName]"
 * on the given lines of the given file. If there should be multiple errors on a line, the line
 * number must appear multiple times. There may not be any errors in any other file.
 */
public void assertErrorsOnLines(String file,
    List<Diagnostic<? extends JavaFileObject>> diagnostics, long... lines) {
  ListMultimap<String, Long> actualErrors = ArrayListMultimap.create();
  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
    String message = diagnostic.getMessage(Locale.US);

    // The source may be null, e.g. for diagnostics about command-line flags
    assertNotNull(message, diagnostic.getSource());
    String sourceName = diagnostic.getSource().getName();

    assertEquals(
        "unexpected error in source file " + sourceName + ": " + message,
        file, sourceName);

    actualErrors.put(diagnostic.getSource().getName(), diagnostic.getLineNumber());

    // any errors from the compiler that are not related to this checker should fail
    assertThat(message).contains("[" + checker.getAnnotation(BugPattern.class).name() + "]");
  }

  assertEquals(
      ImmutableMultiset.copyOf(Longs.asList(lines)),
      ImmutableMultiset.copyOf(actualErrors.get(file)));
}
 
Example 4
@Test
public void testLotsOfRandomInserts() {
    int lots = 50000;
    final FibonacciQueue<Integer> queue = FibonacciQueue.create();
    // Insert lots of random numbers.
    final ImmutableMultiset.Builder<Integer> insertedBuilder = ImmutableMultiset.builder();
    for (int i = 0; i < lots; i++) {
        int r = random.nextInt();
        insertedBuilder.add(r);
        queue.add(r);
    }
    final Multiset<Integer> inserted = insertedBuilder.build();
    assertEquals(lots, queue.size());
    // Ensure it contains the same multiset of values that we put in
    assertEquals(inserted, ImmutableMultiset.copyOf(queue));
    // Ensure the numbers come out in increasing order.
    final List<Integer> polled = Lists.newLinkedList();
    while (!queue.isEmpty()) {
        polled.add(queue.poll());
    }
    assertTrue(Ordering.<Integer>natural().isOrdered(polled));
    // Ensure the same multiset of values came out that we put in
    assertEquals(inserted, ImmutableMultiset.copyOf(polled));
    assertEquals(0, queue.size());
}
 
Example 5
Source Project: batfish   Source File: SpecifiersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolveIpSpaceOfLocationTestDefault() {
  SpecifiersQuestion question = new SpecifiersQuestion(QueryType.IP_SPACE);

  assertThat(
      resolveIpSpaceOfLocation(question, _context).getRows().getData(),
      equalTo(
          ImmutableMultiset.of(
              Row.of(
                  COL_LOCATIONS,
                  ImmutableSet.of(new InterfaceLocation(_c1.getHostname(), _iface1.getName()))
                      .toString(),
                  COL_IP_SPACE,
                  _iface1.getConcreteAddress().getIp().toIpSpace().toString()),
              Row.of(
                  COL_LOCATIONS,
                  ImmutableSet.of(new InterfaceLocation(_c2.getHostname(), _iface2.getName()))
                      .toString(),
                  COL_IP_SPACE,
                  _iface2.getConcreteAddress().getIp().toIpSpace().toString()))));
}
 
Example 6
Source Project: batfish   Source File: SpecifiersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolveIpSpaceOfLocationTest() {
  SpecifiersQuestion questionWithLocation =
      new SpecifiersQuestion(QueryType.IP_SPACE_OF_LOCATION);
  questionWithLocation.setLocationSpecifierInput(_c1.getHostname());

  // only c1:iface1 should be present
  assertThat(
      resolveIpSpaceOfLocation(questionWithLocation, _context).getRows().getData(),
      equalTo(
          ImmutableMultiset.of(
              Row.of(
                  COL_LOCATIONS,
                  ImmutableSet.of(new InterfaceLocation(_c1.getHostname(), _iface1.getName()))
                      .toString(),
                  COL_IP_SPACE,
                  _iface1.getConcreteAddress().getIp().toIpSpace().toString()))));
}
 
Example 7
Source Project: gwt-jackson   Source File: MultisetGwtTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testDeserialization() {
    String input = "{" +
            "\"multiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"hashMultiset\":[\"abc\",\"abc\"]," +
            "\"linkedHashMultiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"sortedMultiset\":[\"foo\",\"abc\",\"bar\",\"abc\",null]," +
            "\"treeMultiset\":[\"bar\",\"abc\",\"abc\",\"foo\",null]," +
            "\"immutableMultiset\":[\"foo\",\"abc\",\"abc\",\"bar\",null]," +
            "\"enumMultiset\":[\"B\",\"A\",\"A\",\"D\",null]" +
            "}";

    BeanWithMultisetTypes result = BeanWithMultisetTypesMapper.INSTANCE.read( input );
    assertNotNull( result );

    List<String> expectedList = Arrays.asList( "foo", "abc", null, "abc" );
    List<String> expectedListWithNonNull = Arrays.asList( "foo", "abc", "bar", "abc" );

    assertEquals( LinkedHashMultiset.create( expectedList ), result.multiset );
    assertEquals( HashMultiset.create( Arrays.asList( "abc", "abc" ) ), result.hashMultiset );
    assertEquals( LinkedHashMultiset.create( expectedList ), result.linkedHashMultiset );
    assertEquals( TreeMultiset.create( expectedListWithNonNull ), result.sortedMultiset );
    assertEquals( TreeMultiset.create( expectedListWithNonNull ), result.treeMultiset );
    assertEquals( ImmutableMultiset.copyOf( expectedListWithNonNull ), result.immutableMultiset );
    assertEquals( EnumMultiset.create( Arrays.asList( AlphaEnum.B, AlphaEnum.A, AlphaEnum.D, AlphaEnum.A ) ), result.enumMultiset );
}
 
Example 8
Source Project: FreeBuilder   Source File: MultisetPropertyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testImmutableSetProperty() {
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("@%s", FreeBuilder.class)
          .addLine("public interface DataType {")
          .addLine("  %s<%s> %s;",
              ImmutableMultiset.class, element.type(), convention.get("items"))
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .addItems(%s)", element.example(0))
          .addLine("    .addItems(%s)", element.example(1))
          .addLine("    .build();")
          .addLine("assertThat(value.%s).iteratesAs(%s);",
              convention.get("items"), element.examples(0, 1))
          .build())
      .runTest();
}
 
Example 9
Source Project: Word2VecJava   Source File: Word2VecTrainer.java    License: MIT License 6 votes vote down vote up
/** @return Tokens with their count, sorted by frequency decreasing, then lexicographically ascending */
private ImmutableMultiset<String> filterAndSort(final Multiset<String> counts) {
	// This isn't terribly efficient, but it is deterministic
	// Unfortunately, Guava's multiset doesn't give us a clean way to order both by count and element
	return Multisets.copyHighestCountFirst(
			ImmutableSortedMultiset.copyOf(
					Multisets.filter(
							counts,
							new Predicate<String>() {
								@Override
								public boolean apply(String s) {
									return counts.count(s) >= minFrequency;
								}
							}
					)
			)
	);
	
}
 
Example 10
Source Project: tac-kbp-eal   Source File: CorpusAnalysis.java    License: MIT License 6 votes vote down vote up
public static ImmutableMultiset<Symbol> toRealisCounts(
    final ImmutableSet<TypeRoleFillerRealis> equivClasses) {
  return Multisets.copyHighestCountFirst(
      ImmutableMultiset.copyOf(Iterables.transform(equivClasses, Functions.compose(RealisSymbol, Realis))));
  /*
  final ImmutableMultimap<KBPRealis, TypeRoleFillerRealis> realisToEquivClass = Multimaps.index(equivClasses, TypeRoleFillerRealis.realisFunction());

  final List<ElementWithCount> elements = Lists.newArrayList();
  for(final Map.Entry<KBPRealis, Collection<TypeRoleFillerRealis>> entry : realisToEquivClass.asMap().entrySet()) {
    elements.add( ElementWithCount.from(entry.getKey(), entry.getValue().size()) );
  }

  Collections.sort(elements, ElementCount);
  return ImmutableList.copyOf(elements);
  */
}
 
Example 11
Source Project: tac-kbp-eal   Source File: CorpusAnalysis.java    License: MIT License 6 votes vote down vote up
public static ImmutableMultiset<Symbol> toMentionTypeCounts(
    final ImmutableSet<TypeRoleFillerRealis> targetEquivClasses,
    final ImmutableMultimap<TypeRoleFillerRealis, AssessedResponse> equivClassToAssessedResponse) {
  final ImmutableMultiset.Builder<Symbol> mentionTypes = ImmutableMultiset.builder();

  for(final TypeRoleFillerRealis equivClass : targetEquivClasses) {
    final AssessedResponse assessedResponse = Collections.max(equivClassToAssessedResponse.get(equivClass), Old2014ID);

    if(assessedResponse.response().role() == TIME) {
      mentionTypes.add(TIME);
    }
    else {
      final Optional<FillerMentionType> mentionType =
          assessedResponse.assessment().mentionTypeOfCAS();
      if (mentionType.isPresent()) {
        mentionTypes.add(Symbol.from(mentionType.get().name()));
      }
    }
  }

  return Multisets.copyHighestCountFirst(mentionTypes.build());
}
 
Example 12
Source Project: tac-kbp-eal   Source File: CorpusAnalysis.java    License: MIT License 6 votes vote down vote up
public static ImmutableMultiset<Symbol> toNumberOfDocsPerEventType(
    final ImmutableSet<TypeRoleFillerRealis> equivClasses) {

  // for each docid, a set of event types
  final ImmutableMap<Symbol, ImmutableSet<Symbol>> eventTypesInEachDoc = getEventTypesInEachDoc(equivClasses);

  final ImmutableMultiset.Builder<Symbol> ret = ImmutableMultiset.builder();

  for(final Map.Entry<Symbol, ImmutableSet<Symbol>> entry : eventTypesInEachDoc.entrySet()) {
    for(final Symbol et : entry.getValue()) {
      ret.add(et);
    }
  }

  return Multisets.copyHighestCountFirst(ret.build());
}
 
Example 13
/**
 * Method should return the number of times an occurrence of a reel
 * 
 * @param reels
 * @return
 */
static int determinePayOutPercentage(List<String> reels) {

	Multiset<String> reelCount = HashMultiset.create();
	reelCount.addAll(reels);

	// order the number of elements by the higest
	ImmutableMultiset<String> highestCountFirst = Multisets.copyHighestCountFirst(reelCount);

	int count = 0;
	for (Entry<String> entry : highestCountFirst.entrySet()) {
		count = entry.getCount();
		break;
	}
	return count;
}
 
Example 14
Source Project: batfish   Source File: FilterTableAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void filterRows() {
  Filter filter = new Filter("col >= 42");
  Rows rows = new Rows();
  rows.add(Row.builder().put("col", null).build());
  rows.add(Row.builder().put("col", 41).build());
  rows.add(Row.builder().put("col", 42).build());
  rows.add(Row.builder().put("col", 43).build());
  Multiset<Row> filteredRows = FilterTableAnswerer.filterRows(filter, rows.getData());

  // we should have the two rows with values >= 42
  assertThat(
      filteredRows,
      equalTo(
          new ImmutableMultiset.Builder<Row>()
              .add(Row.builder().put("col", 42).build())
              .add(Row.builder().put("col", 43).build())
              .build()));
}
 
Example 15
Source Project: batfish   Source File: SpecifiersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolveIpSpaceTest() {
  String prefix = "3.3.3.3/24";

  SpecifiersQuestion questionWithIp = new SpecifiersQuestion(QueryType.LOCATION);
  questionWithIp.setIpSpaceSpecifierInput(prefix);

  // both interface locations should be mapped to 3.3.3.3/24
  assertThat(
      resolveIpSpace(questionWithIp, _context).getRows().getData(),
      equalTo(
          ImmutableMultiset.of(
              Row.of(
                  COL_IP_SPACE,
                  SpecifierFactories.ACTIVE_VERSION == Version.V1
                      ? IpWildcardSetIpSpace.builder()
                          .including(IpWildcard.parse(prefix))
                          .build()
                          .toString()
                      : Prefix.parse(prefix).toIpSpace().toString()))));
}
 
Example 16
Source Project: batfish   Source File: SpecifiersAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void resolveFilterTest() {
  SpecifiersQuestion question = new SpecifiersQuestion(QueryType.FILTER);
  question.setFilterSpecifierInput(_filter1.getName());

  // only filter1 should be present (with a node specifier all nodes are included)
  assertThat(
      resolveFilter(question, _context).getRows().getData(),
      equalTo(
          ImmutableMultiset.of(
              Row.of(
                  COL_NODE, new Node(_c1.getHostname()), COL_FILTER_NAME, _filter1.getName()))));

  // nothing should match since the node specifier does not match anything
  question.setNodeSpecifierInput("foofoo");
  assertThat(
      resolveFilter(question, _context).getRows().getData(), equalTo(ImmutableMultiset.of()));
}
 
Example 17
Source Project: presto   Source File: TestJdbcQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static Multiset<List<Object>> read(ResultSet resultSet)
        throws SQLException
{
    ImmutableMultiset.Builder<List<Object>> result = ImmutableMultiset.builder();
    while (resultSet.next()) {
        ImmutableList.Builder<Object> row = ImmutableList.builder();
        for (int column = 1; column <= resultSet.getMetaData().getColumnCount(); column++) {
            row.add(resultSet.getObject(column));
        }
        result.add(row.build());
    }
    return result.build();
}
 
Example 18
Source Project: presto   Source File: TestPrestoDatabaseMetaData.java    License: Apache License 2.0 5 votes vote down vote up
private void assertMetadataCalls(MetaDataCallback<? extends Collection<List<Object>>> callback, Collection<List<?>> expected, MetadataCallsCount expectedMetadataCallsCount)
        throws Exception
{
    assertMetadataCalls(
            callback,
            actual -> assertThat(ImmutableMultiset.copyOf(requireNonNull(actual, "actual is null")))
                    .isEqualTo(ImmutableMultiset.copyOf(requireNonNull(expected, "expected is null"))),
            expectedMetadataCallsCount);
}
 
Example 19
Source Project: Quicksql   Source File: UtilTest.java    License: MIT License 5 votes vote down vote up
private void checkCompositeMap(String[] beatles, Map<String, Integer> map) {
  assertThat(4, equalTo(map.size()));
  assertThat(false, equalTo(map.isEmpty()));
  assertThat(
      map.keySet(),
      equalTo((Set<String>) new HashSet<String>(Arrays.asList(beatles))));
  assertThat(
      ImmutableMultiset.copyOf(map.values()),
      equalTo(ImmutableMultiset.copyOf(Arrays.asList(4, 4, 6, 5))));
}
 
Example 20
Source Project: Strata   Source File: GuavateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_toImmutableMultiset() {
  List<String> list = Arrays.asList("a", "ab", "b", "bb", "c", "a");
  ImmutableMultiset<String> test = list.stream()
      .filter(s -> s.length() == 1)
      .collect(Guavate.toImmutableMultiset());
  assertThat(test).isEqualTo(ImmutableMultiset.of("a", "a", "b", "c"));
}
 
Example 21
Source Project: Quicksql   Source File: RelMdColumnOriginsTest.java    License: MIT License 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-542">[CALCITE-542]
 * Support for Aggregate with grouping sets in RelMdColumnOrigins</a>. */
@Test public void testQueryWithAggregateGroupingSets() throws Exception {
  Connection connection = DriverManager.getConnection("jdbc:calcite:");
  CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);

  calciteConnection.getRootSchema().add("T1",
      new TableInRootSchemaTest.SimpleTable());
  Statement statement = calciteConnection.createStatement();
  ResultSet resultSet =
      statement.executeQuery("SELECT TABLE1.ID, TABLE2.ID FROM "
              + "(SELECT GROUPING(A) AS ID FROM T1 "
              + "GROUP BY ROLLUP(A,B)) TABLE1 "
              + "JOIN "
              + "(SELECT GROUPING(A) AS ID FROM T1 "
              + "GROUP BY ROLLUP(A,B)) TABLE2 "
              + "ON TABLE1.ID = TABLE2.ID");

  final String result1 = "ID=0; ID=0";
  final String result2 = "ID=1; ID=1";
  final ImmutableMultiset<String> expectedResult =
      ImmutableMultiset.<String>builder()
          .addCopies(result1, 25)
          .add(result2)
          .build();
  assertThat(CalciteAssert.toSet(resultSet), equalTo(expectedResult));

  final ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
  assertThat(resultSetMetaData.getColumnName(1), equalTo("ID"));
  assertThat(resultSetMetaData.getTableName(1), nullValue());
  assertThat(resultSetMetaData.getSchemaName(1), nullValue());
  assertThat(resultSetMetaData.getColumnName(2), equalTo("ID"));
  assertThat(resultSetMetaData.getTableName(2), nullValue());
  assertThat(resultSetMetaData.getSchemaName(2), nullValue());
  resultSet.close();
  statement.close();
  connection.close();
}
 
Example 22
private Multiset<Type> fieldCardinalities(ClassFile cf)
{
	List<Type> t = cf.getFields().stream()
		.filter(f -> !f.isStatic())
		.map(f -> f.getType())
		.collect(Collectors.toList());

	return ImmutableMultiset.copyOf(t);
}
 
Example 23
private Multiset<Signature> methodCardinalities(ClassFile cf)
{
	List<Signature> t = cf.getMethods().stream()
		.filter(m -> !m.isStatic())
		.filter(m -> !m.getName().startsWith("<"))
		.map(m -> m.getDescriptor())
		.collect(Collectors.toList());

	return ImmutableMultiset.copyOf(t);
}
 
Example 24
Source Project: timbuctoo   Source File: UserCreationTask.java    License: GNU General Public License v3.0 5 votes vote down vote up
private List<String> getDuplicateKeys(ImmutableMultimap<String, String> immutableMultimap) {
  ImmutableMultiset<String> keys = immutableMultimap.keys();
  LOG.debug("keys: {}", keys);
  Set<String> uniques = Sets.newHashSet();
  return keys.stream()
             .filter(key -> !uniques.add(key)).distinct()
             .collect(toList());
}
 
Example 25
/**
 * Copies contents into an immutable <tt>Multiset</tt> view.
 *
 * @return a copied view of all keys, with counts for each one of them
 */
@Override
public Multiset<K> keys() {
    final ImmutableMultiset.Builder<K> builder = ImmutableMultiset.builder();
    entries.forEach((key, values) -> builder.setCount(key, values.size()));
    return builder.build();
}
 
Example 26
Source Project: codebuff   Source File: MediaType.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Map<String, ImmutableMultiset<String>> parametersAsMap() {
          return Maps.transformValues(parameters.asMap(), new Function<Collection<String>, ImmutableMultiset<String>>() {
                                                            @Override
                                                            public ImmutableMultiset<String> apply(Collection<String> input) {
                                                              return ImmutableMultiset.copyOf(input);
                                                            }
                                                          });
}
 
Example 27
Source Project: vespa   Source File: SpanTree.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean annotationsEquals(SpanTree tree) {
    List<Annotation> annotationCollection = new LinkedList<Annotation>(getAnnotations());
    List<Annotation> otherAnnotations = new LinkedList<Annotation>(tree.getAnnotations());

    return annotationCollection.size() == otherAnnotations.size() &&
            ImmutableMultiset.copyOf(annotationCollection).equals(ImmutableMultiset.copyOf(otherAnnotations));
}
 
Example 28
Source Project: attic-aurora   Source File: AttributeAggregate.java    License: Apache License 2.0 5 votes vote down vote up
public void updateAttributeAggregate(IHostAttributes attributes) {
  final Supplier<Multiset<Pair<String, String>>> previous = aggregate;
  aggregate = Suppliers.memoize(
      () -> {
        ImmutableMultiset.Builder<Pair<String, String>> builder
            = new ImmutableMultiset.Builder<>();
        builder.addAll(previous.get());
        addAttributes(builder, attributes.getAttributes());
        return builder.build();
      }
  );
}
 
Example 29
Source Project: batfish   Source File: FilterLineReachabilityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWithIcmpType() {
  // First line accepts IP 1.2.3.4
  // Second line accepts same but only ICMP of type 8
  List<AclLine> lines =
      ImmutableList.of(
          ExprAclLine.acceptingHeaderSpace(
              HeaderSpace.builder().setSrcIps(Ip.parse("1.2.3.4").toIpSpace()).build()),
          ExprAclLine.acceptingHeaderSpace(
              HeaderSpace.builder()
                  .setSrcIps(Ip.parse("1.2.3.4").toIpSpace())
                  .setIpProtocols(ImmutableSet.of(IpProtocol.ICMP))
                  .setIcmpTypes(ImmutableList.of(new SubRange(8)))
                  .build()));
  _aclb.setLines(lines).setName("acl").build();
  List<String> lineNames = lines.stream().map(Object::toString).collect(Collectors.toList());

  TableAnswerElement answer = answer(new FilterLineReachabilityQuestion());

  // Construct the expected result. First line should block second.
  Multiset<Row> expected =
      ImmutableMultiset.of(
          Row.builder(COLUMN_METADATA)
              .put(COL_SOURCES, ImmutableList.of(_c1.getHostname() + ": acl"))
              .put(COL_UNREACHABLE_LINE, lineNames.get(1))
              .put(COL_UNREACHABLE_LINE_ACTION, LineAction.PERMIT)
              .put(COL_BLOCKING_LINES, ImmutableList.of(lineNames.get(0)))
              .put(COL_DIFF_ACTION, false)
              .put(COL_REASON, BLOCKING_LINES)
              .build());
  assertThat(answer.getRows().getData(), equalTo(expected));
}
 
Example 30
/**
 * Calculate the usage of each system
 * 
 * @return
 * @throws ZookeeperException
 * @throws ZookeeperNotFoundException 
 * @throws BBoxDBException 
 */
protected Multiset<BBoxDBInstance> calculateSystemUsage() 
		throws ZookeeperException, ZookeeperNotFoundException, BBoxDBException {
			
	final DistributionGroupAdapter zookeeperAdapter 
		= ZookeeperClientFactory.getZookeeperClient().getDistributionGroupAdapter();
	
	final List<String> distributionGroups = zookeeperAdapter.getDistributionGroups();
	
	// The overall usage
    final ImmutableMultiset.Builder<BBoxDBInstance> builder = ImmutableMultiset.builder();
    
	// Calculate usage for each distribution group
	for(final String groupName : distributionGroups) {
		final SpacePartitioner spacepartitioner = SpacePartitionerCache
			.getInstance().getSpacePartitionerForGroupName(groupName);
		
		final DistributionRegion region = spacepartitioner.getRootNode();
		final Multiset<BBoxDBInstance> regionSystemUsage 
			= DistributionRegionHelper.getSystemUtilization(region);
	
		// Merge results
		builder.addAll(regionSystemUsage);
	}
	
    return builder.build();
}