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

The following examples show how to use com.google.common.collect.ImmutableMultimap. 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: emodb   Source File: DefaultFanoutTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnauthorizedFanout() {
    addTable("unauthorized-table");

    OwnedSubscription subscription = new DefaultOwnedSubscription(
            "test", Conditions.intrinsic(Intrinsic.TABLE, Conditions.equal("unauthorized-table")),
            new Date(), Duration.ofDays(1), "owner0");

    EventData event = newEvent("id0", "unauthorized-table", "key0");

    when(_subscriptionsSupplier.get()).thenReturn(ImmutableList.of(subscription));
    DatabusAuthorizer.DatabusAuthorizerByOwner authorizerByOwner = mock(DatabusAuthorizer.DatabusAuthorizerByOwner.class);
    when(authorizerByOwner.canReceiveEventsFromTable("matching-table")).thenReturn(false);
    when(_databusAuthorizer.owner("owner0")).thenReturn(authorizerByOwner);

    _defaultFanout.copyEvents(ImmutableList.of(event));

    // Event is not authorized for owner, should only go to remote fanout
    assertEquals(_eventsSinked,
            ImmutableMultimap.of(_remoteChannel, event.getData()));

}
 
Example 2
@Test //only a single unifier exists
public void testUnification_EXACT_BinaryRelationWithTypes_SomeVarsHaveTypes_UnifierMatchesTypes() {
    try (Transaction tx = unificationWithTypesSession.transaction(Transaction.Type.READ)) {
        ReasonerQueryFactory reasonerQueryFactory = ((TestTransactionProvider.TestTransaction) tx).reasonerQueryFactory();

        ReasonerAtomicQuery parentQuery = reasonerQueryFactory.atomic(conjunction("{ $x1 isa twoRoleEntity;($x1, $x2) isa binary; };"));
        ReasonerAtomicQuery childQuery = reasonerQueryFactory.atomic(conjunction("{ $y1 isa twoRoleEntity;($y1, $y2) isa binary; };"));

        MultiUnifier unifier = childQuery.getMultiUnifier(parentQuery);
        MultiUnifier correctUnifier = new MultiUnifierImpl(ImmutableMultimap.of(
                new Variable("y1"), new Variable("x1"),
                new Variable("y2"), new Variable("x2")
        ));
        assertEquals(correctUnifier, unifier);
    }
}
 
Example 3
Source Project: nomulus   Source File: SetNumInstancesCommandTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_noNonLiveVersions_succeeds() throws Exception {
  command.appengine =
      new AppEngineAdminApiHelper.Builder()
          .setAppId(projectId)
          .setManualScalingVersionsMap(
              ImmutableMultimap.of(
                  "default", "version1", "default", "version2", "default", "version3"))
          .setLiveVersionsMap(
              ImmutableMultimap.of(
                  "default", "version1", "default", "version2", "default", "version3"))
          .build()
          .getAppengine();

  runCommand("--non_live_versions=true", "--services=DEFAULT", "--num_instances=10");
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version1", 10L);
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version2", 10L);
  verify(appEngineServiceUtils, times(0)).setNumInstances("default", "version3", 10L);
}
 
Example 4
Source Project: glowroot   Source File: ClasspathCache.java    License: Apache License 2.0 6 votes vote down vote up
synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap =
                MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}
 
Example 5
Source Project: nomulus   Source File: ReadDnsQueueActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_corruptTaskTldMismatch_published() {
  // TODO(mcilwain): what's the correct action to take in this case?
  dnsQueue.addDomainRefreshTask("domain.com");
  dnsQueue.addDomainRefreshTask("domain.example");
  QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
      .add(
          TaskOptions.Builder.withDefaults()
              .method(Method.PULL)
              .param(DNS_TARGET_TYPE_PARAM, TargetType.DOMAIN.toString())
              .param(DNS_TARGET_NAME_PARAM, "domain.wrongtld")
              .param(DNS_TARGET_CREATE_TIME_PARAM, "3000-01-01TZ")
              .param(PARAM_TLD, "net"));

  run();

  assertNoTasksEnqueued(DNS_PULL_QUEUE_NAME);
  assertTldsEnqueuedInPushQueue(
      ImmutableMultimap.of("com", "comWriter", "example", "exampleWriter", "net", "netWriter"));
}
 
Example 6
/**
 * Build the {@link ImmutableMultimap} using the given builder.
 *
 * @param reader {@link JsonReader} used to read the JSON input
 * @param ctx Context for the full deserialization process
 * @param params Parameters for this deserialization
 * @param builder {@link ImmutableMultimap.Builder} used to collect the entries
 */
protected void buildMultimap( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params,
                              ImmutableMultimap.Builder<K, V> builder ) {
    reader.beginObject();
    while ( JsonToken.END_OBJECT != reader.peek() ) {
        String name = reader.nextName();
        K key = keyDeserializer.deserialize( name, ctx );
        reader.beginArray();
        while ( JsonToken.END_ARRAY != reader.peek() ) {
            V value = valueDeserializer.deserialize( reader, ctx, params );
            builder.put( key, value );
        }
        reader.endArray();
    }
    reader.endObject();
}
 
Example 7
Source Project: nomulus   Source File: ReadDnsQueueActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_corruptTaskWrongType_discarded() {
  dnsQueue.addDomainRefreshTask("domain.com");
  dnsQueue.addDomainRefreshTask("domain.example");
  QueueFactory.getQueue(DNS_PULL_QUEUE_NAME)
      .add(
          TaskOptions.Builder.withDefaults()
              .method(Method.PULL)
              .param(DNS_TARGET_TYPE_PARAM, "Wrong type")
              .param(DNS_TARGET_NAME_PARAM, "domain.net")
              .param(PARAM_TLD, "net"));

  run();

  // The corrupt task isn't in the pull queue, but also isn't in the push queue
  assertNoTasksEnqueued(DNS_PULL_QUEUE_NAME);
  assertTldsEnqueuedInPushQueue(
      ImmutableMultimap.of("com", "comWriter", "example", "exampleWriter"));
}
 
Example 8
Source Project: micro-server   Source File: GuavaAppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void startServer() {
	stream = simpleReact.ofAsync(
			() -> server = new MicroserverApp(GuavaAppTest.class,
					() -> "guava-app")).then(server -> server.start());

	entity = ImmutableGuavaEntity.builder().value("value")
			.list(ImmutableList.of("hello", "world"))
			.mapOfSets(ImmutableMap.of("key1", ImmutableSet.of(1, 2, 3)))
			.multiMap(ImmutableMultimap.of("1", 2, "1", 2, "2", 4)).build();

	JacksonUtil.convertFromJson(JacksonUtil.serializeToJson(entity),
			ImmutableGuavaEntity.class);

	present = Jdk8Entity.builder().name(Optional.of("test")).build();

	JacksonUtil.convertFromJson(JacksonUtil.serializeToJson(present),
			Optional.class);
	absent = Jdk8Entity.builder().name(Optional.empty()).build();
}
 
Example 9
Source Project: presto   Source File: StatementAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
private Multimap<QualifiedName, Expression> extractNamedOutputExpressions(Select node)
{
    // Compute aliased output terms so we can resolve order by expressions against them first
    ImmutableMultimap.Builder<QualifiedName, Expression> assignments = ImmutableMultimap.builder();
    for (SelectItem item : node.getSelectItems()) {
        if (item instanceof SingleColumn) {
            SingleColumn column = (SingleColumn) item;
            Optional<Identifier> alias = column.getAlias();
            if (alias.isPresent()) {
                assignments.put(QualifiedName.of(alias.get().getValue()), column.getExpression()); // TODO: need to know if alias was quoted
            }
            else if (column.getExpression() instanceof Identifier) {
                assignments.put(QualifiedName.of(((Identifier) column.getExpression()).getValue()), column.getExpression());
            }
        }
    }

    return assignments.build();
}
 
Example 10
Source Project: batfish   Source File: ParseWarningAnswererTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAggregateRow() {
  Row row =
      getAggregateRow(
          new ParseWarningTriplet("dup", "[configuration]", null),
          ImmutableMultimap.of("f1", 3, "f1", 4, "f2", 23),
          createMetadata(new ParseWarningQuestion(true)).toColumnMap());

  Row expected =
      Row.of(
          COL_FILELINES,
          ImmutableList.of(
              new FileLines("f1", ImmutableSortedSet.of(3, 4)),
              new FileLines("f2", ImmutableSortedSet.of(23))),
          COL_TEXT,
          "dup",
          COL_PARSER_CONTEXT,
          "[configuration]",
          COL_COMMENT,
          "(not provided)");

  assertThat(row, equalTo(expected));
}
 
Example 11
Source Project: presto   Source File: TestLocalDynamicFilterConsumer.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNone()
        throws ExecutionException, InterruptedException
{
    LocalDynamicFilterConsumer filter = new LocalDynamicFilterConsumer(
            ImmutableMultimap.of(new DynamicFilterId("123"), new Symbol("a")),
            ImmutableMap.of(new DynamicFilterId("123"), 0),
            ImmutableMap.of(new DynamicFilterId("123"), INTEGER),
            1);
    assertEquals(filter.getBuildChannels(), ImmutableMap.of(new DynamicFilterId("123"), 0));
    Consumer<TupleDomain<DynamicFilterId>> consumer = filter.getTupleDomainConsumer();
    ListenableFuture<Map<Symbol, Domain>> result = filter.getNodeLocalDynamicFilterForSymbols();

    assertFalse(result.isDone());
    consumer.accept(TupleDomain.none());

    assertEquals(result.get(), ImmutableMap.of(
            new Symbol("a"), Domain.none(INTEGER)));
}
 
Example 12
Source Project: james-project   Source File: MessageIdMapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void deletesShouldUpdateMessageCount() throws Exception {
    saveMessages();

    SimpleMailboxMessage copiedMessage = SimpleMailboxMessage.copy(benwaWorkMailbox.getMailboxId(), message1);
    copiedMessage.setUid(mapperProvider.generateMessageUid());
    copiedMessage.setModSeq(mapperProvider.generateModSeq(benwaWorkMailbox));
    sut.copyInMailbox(copiedMessage, benwaWorkMailbox);

    sut.delete(
        ImmutableMultimap.<MessageId, MailboxId>builder()
            .put(message1.getMessageId(), benwaWorkMailbox.getMailboxId())
            .put(message2.getMessageId(), benwaInboxMailbox.getMailboxId())
            .build());

    assertThat(messageMapper.countMessagesInMailbox(benwaInboxMailbox))
        .isEqualTo(2);
}
 
Example 13
@Test(expected = UserCreationException.class)
public void executeRethrowsTheExceptionsOfTheLocalUserCreator() throws Exception {
  doThrow(new UserCreationException("")).when(localUserCreator).create(ArgumentMatchers.any());
  ImmutableMultimap<String, String> immutableMultimap = ImmutableMultimap.<String, String>builder()
    .put(UserInfoKeys.USER_PID, PID)
    .put(UserInfoKeys.USER_NAME, USER_NAME)
    .put(UserInfoKeys.PASSWORD, PWD)
    .put(UserInfoKeys.GIVEN_NAME, GIVEN_NAME)
    .put(UserInfoKeys.SURNAME, SURNAME)
    .put(UserInfoKeys.EMAIL_ADDRESS, EMAIL)
    .put(UserInfoKeys.ORGANIZATION, ORGANIZATION)
    .put(UserInfoKeys.VRE_ID, VRE_ID)
    .put(UserInfoKeys.VRE_ROLE, VRE_ROLE)
    .build();

  instance.execute(immutableMultimap, mock(PrintWriter.class));
}
 
Example 14
Source Project: emodb   Source File: DedupMigrationTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    boolean oldEnabled = _dedupEnabled.get();
    boolean newEnabled = oldEnabled;

    for (String value : parameters.get("dedup")) {
        newEnabled = Boolean.parseBoolean(value);
        _dedupEnabled.set(newEnabled);
    }

    out.printf("dedup-enabled: %s%n", newEnabled);

    Collection<String> migrations = parameters.get("migrate");
    if (!migrations.isEmpty()) {
        if (newEnabled) {
            out.println("Ignoring migrations since Databus dedup is still enabled.");
        } else {
            if (oldEnabled) {
                out.println("Sleeping 15 seconds to allow in-flight requests to complete.");
                out.flush();
                Thread.sleep(Duration.seconds(15).toMilliseconds());
            }
            migrate(migrations, out);
        }
    }
}
 
Example 15
Source Project: bazel   Source File: ParallelVisitorTest.java    License: Apache License 2.0 6 votes vote down vote up
private RecordingParallelVisitor(
    ImmutableMultimap<String, String> successors,
    RecordingCallback recordingCallback,
    int visitBatchSize,
    int processResultsBatchSize) {
  super(
      recordingCallback,
      SampleException.class,
      visitBatchSize,
      processResultsBatchSize,
      MIN_PENDING_TASKS,
      BATCH_CALLBACK_SIZE,
      Executors.newFixedThreadPool(3),
      VisitTaskStatusCallback.NULL_INSTANCE);
  this.successorMap = successors;
}
 
Example 16
@Test
public void executeDoesNotImportIfKeysAreMissing() throws Exception {
  // Missing USER_PID key
  ImmutableMultimap<String, String> immutableMultimap = ImmutableMultimap.<String, String>builder()
    .put(UserInfoKeys.USER_NAME, USER_NAME)
    .put(UserInfoKeys.PASSWORD, PWD)
    .put(UserInfoKeys.GIVEN_NAME, GIVEN_NAME)
    .put(UserInfoKeys.SURNAME, SURNAME)
    .put(UserInfoKeys.EMAIL_ADDRESS, EMAIL)
    .put(UserInfoKeys.ORGANIZATION, ORGANIZATION)
    .put(UserInfoKeys.VRE_ID, VRE_ID)
    .put(UserInfoKeys.VRE_ROLE, VRE_ROLE)
    .build();

  instance.execute(immutableMultimap, printWriter);

  verifyZeroInteractions(localUserCreator);
  verify(printWriter).write(argThat(containsString(UserInfoKeys.USER_PID)));
}
 
Example 17
Source Project: bundletool   Source File: ApkMatcher.java    License: Apache License 2.0 6 votes vote down vote up
private Predicate<String> getModuleNameMatcher(Variant variant, Version bundleVersion) {
  if (requestedModuleNames.isPresent()) {
    ImmutableMultimap<String, String> moduleDependenciesMap = buildAdjacencyMap(variant);

    HashSet<String> dependencyModules = new HashSet<>(requestedModuleNames.get());
    for (String requestedModuleName : requestedModuleNames.get()) {
      addModuleDependencies(requestedModuleName, moduleDependenciesMap, dependencyModules);
    }

    if (matchInstant) {
      return dependencyModules::contains;
    } else {
      return Predicates.or(
          buildModulesDeliveredInstallTime(variant, bundleVersion)::contains,
          dependencyModules::contains);
    }
  } else {
    if (matchInstant) {
      // For instant matching, by default all instant modules are matched.
      return Predicates.alwaysTrue();
    } else {
      // For conventional matching, only install-time modules are matched.
      return buildModulesDeliveredInstallTime(variant, bundleVersion)::contains;
    }
  }
}
 
Example 18
Source Project: FreeBuilder   Source File: SetMultimapPropertyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRemove_doesNotThrowIfEntryNotPresent() {
  behaviorTester
      .with(new Processor(features))
      .with(dataType)
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putAllItems(%s.of(", ImmutableMultimap.class)
          .addLine("        %s, %s,", key.example(0), value.example(1))
          .addLine("        %s, %s))", key.example(3), value.example(2))
          .addLine("    .removeItems(%s, %s)", key.example(0), value.example(2))
          .addLine("    .build();")
          .addLine("assertThat(value.%s)", convention.get("items"))
          .addLine("    .contains(%s, %s)", key.example(0), value.example(1))
          .addLine("    .and(%s, %s)", key.example(3), value.example(2))
          .addLine("    .andNothingElse()")
          .addLine("    .inOrder();")
          .build())
      .runTest();
}
 
Example 19
Source Project: riptide   Source File: RequesterTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldExpandOnGetWithHeaders() {
    expectRequestTo("https://api.example.com/123");

    unit.get("/123")
            .headers(ImmutableMultimap.of())
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()))
            .join();
}
 
Example 20
Source Project: codebuff   Source File: ServiceManager.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
ImmutableMultimap<State, Service> servicesByState() {
  ImmutableSetMultimap.Builder<State, Service> builder = ImmutableSetMultimap.builder();
  monitor.enter();
  try {
    for (Entry<State, Service> entry : servicesByState.entries()) {
      if (!(entry.getValue() instanceof NoOpService)) {
        builder.put(entry);
      }
    }
  } finally {
    monitor.leave();
  }
  return builder.build();
}
 
Example 21
@Test
void testCreateRfdModelDECIMAL() {
  // Model createRdfModel(String subjectIRI, Entity objectEntity)
  Entity objectEntity = mock(Entity.class);
  EntityType entityType = mock(EntityType.class);

  Attribute attribute = mock(Attribute.class);
  List<Attribute> attributeList = singletonList(attribute);

  when(objectEntity.getEntityType()).thenReturn(entityType);
  double value = 10.0;
  when(objectEntity.get("attributeName")).thenReturn(value);
  when(objectEntity.getDouble("attributeName")).thenReturn(value);

  when(entityType.getAtomicAttributes()).thenReturn(attributeList);
  when(attribute.getName()).thenReturn("attributeName");

  when(attribute.getDataType()).thenReturn(AttributeType.DECIMAL);

  LabeledResource tag = new LabeledResource("http://IRI.nl", "tag label");
  Multimap<Relation, LabeledResource> tags = ImmutableMultimap.of(Relation.isAssociatedWith, tag);
  when(tagService.getTagsForAttribute(entityType, attribute)).thenReturn(tags);

  Model result =
      writer.createRdfModel("http://molgenis01.gcc.rug.nl/fdp/catolog/test/this", objectEntity);

  assertEquals(1, result.size());
  Iterator results = result.iterator();
  assertEquals(
      "(http://molgenis01.gcc.rug.nl/fdp/catolog/test/this, http://IRI.nl, \"10.0\"^^<http://www.w3.org/2001/XMLSchema#double>) [null]",
      results.next().toString());
}
 
Example 22
Source Project: mug   Source File: BiStreamTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void testBiStreamWithKeyAndValueFunctions() {
  assertKeyValues(BiStream.from(Stream.of(1, 2), Object::toString, v -> v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("1", 1, "2", 2))
      .inOrder();
  assertKeyValues(BiStream.from(Stream.of(1, 2).parallel(), Object::toString, v -> v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("1", 1, "2", 2))
      .inOrder();
}
 
Example 23
Source Project: tac-kbp-eal   Source File: KBPSpec2016LinkingLoader.java    License: MIT License 5 votes vote down vote up
@Override
protected void handleResponseSetIDs(final ResponseLinking.Builder responseLinking,
    final ImmutableSet<ResponseSet> responseSets,
    final ImmutableMap<String, ResponseSet> responseIDs,
    final Optional<ImmutableMap.Builder<String, String>> foreignLinkingIdToLocal)
    throws IOException {
  if (responseSets.size() == responseIDs.size()) {
    responseLinking.responseSetIds(ImmutableBiMap.copyOf(responseIDs));
    responseLinking.build();
  } else if (responseSets.size() > responseIDs.size() || !foreignLinkingIdToLocal.isPresent()) {
    throw new IOException("Read " + responseSets.size() + " response sets but "
        + responseIDs.size() + " ID assignments");
  } else {
    log.warn(
        "Warning - converting ResponseSet IDs and saving them, this is almost definitely an error!");
    final ImmutableMultimap<ResponseSet, String> responseSetToIds =
        responseIDs.asMultimap().inverse();
    final LaxImmutableMapBuilder<String, ResponseSet> idsMapB =
        MapUtils.immutableMapBuilderAllowingSameEntryTwice();

    for (final Map.Entry<ResponseSet, Collection<String>> setAndIds : responseSetToIds.asMap()
        .entrySet()) {

      final Collection<String> ids = setAndIds.getValue();
      final String selectedID =
          checkNotNull(getFirst(usingToString().immutableSortedCopy(ids), null));
      for (final String oldId : ids) {
        log.debug("Selecting id {} for cluster {}", selectedID, oldId);
        foreignLinkingIdToLocal.get().put(oldId, selectedID);
        idsMapB.put(selectedID, responseIDs.get(oldId));
      }
    }
    responseLinking.responseSetIds(ImmutableBiMap.copyOf(idsMapB.build()));
  }
}
 
Example 24
Source Project: FreeBuilder   Source File: ListMultimapProperty.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ListMultimapProperty> create(Config config) {
  Property property = config.getProperty();
  DeclaredType type = maybeDeclared(property.getType()).orElse(null);
  if (!erasesToAnyOf(type,
      Multimap.class,
      ImmutableMultimap.class,
      ListMultimap.class,
      ImmutableListMultimap.class)) {
    return Optional.empty();
  }

  TypeMirror keyType = upperBound(config.getElements(), type.getTypeArguments().get(0));
  TypeMirror valueType = upperBound(config.getElements(), type.getTypeArguments().get(1));
  Optional<TypeMirror> unboxedKeyType = maybeUnbox(keyType, config.getTypes());
  Optional<TypeMirror> unboxedValueType = maybeUnbox(valueType, config.getTypes());
  boolean overridesPutMethod = hasPutMethodOverride(
      config, unboxedKeyType.orElse(keyType), unboxedValueType.orElse(valueType));

  FunctionalType mutatorType = functionalTypeAcceptedByMethod(
      config.getBuilder(),
      mutator(property),
      consumer(listMultimap(keyType, valueType, config.getElements(), config.getTypes())),
      config.getElements(),
      config.getTypes());

  return Optional.of(new ListMultimapProperty(
      config.getDatatype(),
      property,
      overridesPutMethod,
      keyType,
      unboxedKeyType,
      valueType,
      unboxedValueType,
      mutatorType));
}
 
Example 25
private boolean huRowReservationMatchesPackageableRow(@NonNull final HUEditorRow huRow)
{
	final Optional<OrderLineId> orderLineId = Optional
			.ofNullable(getSingleSelectedPackageableRowOrNull())
			.flatMap(PackageableRow::getSalesOrderLineId);

	final ImmutableMultimap<OrderLineId, HUEditorRow> //
	includedOrderLineReservations = huRow.getIncludedOrderLineReservations();

	if (orderLineId.isPresent())
	{
		final int numberOfOrderLineIds = includedOrderLineReservations.keySet().size();
		final boolean reservedForMoreThanOneOrderLine = numberOfOrderLineIds > 1;
		if (reservedForMoreThanOneOrderLine)
		{
			return false;
		}
		else if (numberOfOrderLineIds == 1)
		{
			final boolean reservedForDifferentOrderLine = !includedOrderLineReservations.containsKey(orderLineId.get());
			if (reservedForDifferentOrderLine)
			{
				return false;
			}
		}
	}
	else
	{
		final boolean rowHasHuWithReservation = !includedOrderLineReservations.isEmpty();
		if (rowHasHuWithReservation)
		{
			return false;
		}
	}
	return true;
}
 
Example 26
Source Project: cloudbreak   Source File: UsersStateDifference.java    License: Apache License 2.0 5 votes vote down vote up
public static ImmutableMultimap<String, String> calculateGroupMembershipToRemove(UmsUsersState umsState, UsersState ipaState) {
    Multimap<String, String> groupMembershipToRemove = HashMultimap.create();
    ipaState.getGroupMembership().forEach((group, user) -> {
        if (!FreeIpaChecks.IPA_UNMANAGED_GROUPS.contains(group) && !umsState.getUsersState().getGroupMembership().containsEntry(group, user)) {
            LOGGER.debug("removing user : {} to group : {}", user, group);
            groupMembershipToRemove.put(group, user);
        }
    });

    LOGGER.info("groupMembershipToRemove size = {}", groupMembershipToRemove.size());
    LOGGER.debug("groupMembershipToRemove = {}", groupMembershipToRemove.asMap());

    return ImmutableMultimap.copyOf(groupMembershipToRemove);
}
 
Example 27
Source Project: attic-stratos   Source File: SpotInstanceApiMockTest.java    License: Apache License 2.0 5 votes vote down vote up
public void describeSpotInstanceRequestsInRegionWithFilter_404() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));

   assertEquals(spotApi().describeSpotInstanceRequestsInRegionWithFilter(DEFAULT_REGION,
         ImmutableMultimap.of("instance-id", "i-ef308e8e")), ImmutableSet.of());

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION, "Action=DescribeSpotInstanceRequests&Filter.1.Name=instance-id&Filter.1.Value.1=i-ef308e8e");
}
 
Example 28
Source Project: buck   Source File: AndroidAppModularityGraphEnhancer.java    License: Apache License 2.0 5 votes vote down vote up
AndroidAppModularityGraphEnhancementResult createAdditionalBuildables() {

    ImmutableSortedSet.Builder<BuildRule> enhancedDeps = ImmutableSortedSet.naturalOrder();
    enhancedDeps.addAll(originalDeps);

    AndroidPackageableCollector collector =
        new AndroidPackageableCollector(
            originalBuildTarget,
            buildTargetsToExcludeFromDex,
            apkModuleGraph,
            AndroidPackageableFilterFactory.createForNonNativeTargets(
                configurationRuleRegistry, originalBuildTarget));
    collector.addPackageables(
        AndroidPackageableCollector.getPackageableRules(originalDeps), ruleResolver);
    AndroidPackageableCollection packageableCollection = collector.build();

    enhancedDeps.addAll(getTargetsAsRules(packageableCollection.getJavaLibrariesToDex()));

    // Add dependencies on all the build rules generating third-party JARs.  This is mainly to
    // correctly capture deps when a prebuilt_jar forwards the output from another build rule.
    enhancedDeps.addAll(
        ruleResolver.filterBuildRuleInputs(
            packageableCollection
                .getPathsToThirdPartyJars()
                .get(apkModuleGraph.getRootAPKModule())));

    Optional<ImmutableMultimap<APKModule, String>> moduleToSharedLibrary =
        shouldIncludeLibraries
            ? Optional.of(buildModuleToSharedLibraries(packageableCollection))
            : Optional.empty();

    return ImmutableAndroidAppModularityGraphEnhancementResult.builder()
        .setPackageableCollection(packageableCollection)
        .setFinalDeps(enhancedDeps.build())
        .setAPKModuleGraph(apkModuleGraph)
        .setModulesToSharedLibraries(moduleToSharedLibrary)
        .build();
  }
 
Example 29
Source Project: nomulus   Source File: ReadDnsQueueActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_twoDnsWriters() {
  persistResource(
      Registry.get("com")
          .asBuilder()
          .setDnsWriters(ImmutableSet.of("comWriter", "otherWriter"))
          .build());
  dnsQueue.addDomainRefreshTask("domain.com");

  run();

  assertNoTasksEnqueued(DNS_PULL_QUEUE_NAME);
  assertTldsEnqueuedInPushQueue(ImmutableMultimap.of("com", "comWriter", "com", "otherWriter"));
}
 
Example 30
Source Project: takari-lifecycle   Source File: Classpath.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static Multimap<String, ClasspathEntry> newPackageIndex(List<ClasspathEntry> entries) {
  Multimap<String, ClasspathEntry> classpath = LinkedHashMultimap.create();
  for (ClasspathEntry entry : entries) {
    for (String packageName : entry.getPackageNames()) {
      classpath.put(packageName, entry);
    }
  }
  return ImmutableMultimap.copyOf(classpath); // preserves order
}