com.google.common.collect.MultimapBuilder Java Examples

The following examples show how to use com.google.common.collect.MultimapBuilder. 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 Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardBackplane.java    License: Apache License 2.0 6 votes vote down vote up
private void startSubscriptionThread() {
  ListMultimap<String, TimedWatchFuture> watchers =
      Multimaps.synchronizedListMultimap(
          MultimapBuilder.linkedHashKeys().arrayListValues().build());
  subscriberService = Executors.newFixedThreadPool(32);
  subscriber =
      new RedisShardSubscriber(watchers, workerSet, config.getWorkerChannel(), subscriberService);

  operationSubscription =
      new RedisShardSubscription(
          subscriber,
          /* onUnsubscribe=*/ () -> {
            subscriptionThread = null;
            if (onUnsubscribe != null) {
              onUnsubscribe.runInterruptibly();
            }
          },
          /* onReset=*/ this::updateWatchedIfDone,
          /* subscriptions=*/ subscriber::subscribedChannels,
          client);

  // use Executors...
  subscriptionThread = new Thread(operationSubscription);

  subscriptionThread.start();
}
 
Example #2
Source Project: bazel-buildfarm   Author: bazelbuild   File: GrpcCASTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void putAddsExpiration() throws IOException, InterruptedException {
  ByteString uploadContent = ByteString.copyFromUtf8("uploaded");
  Digest digest = DIGEST_UTIL.compute(uploadContent);
  String instanceName = "test";
  ListMultimap<Digest, Runnable> onExpirations =
      MultimapBuilder.hashKeys().arrayListValues().build();
  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ByteStreamUploader uploader = mock(ByteStreamUploader.class);
  GrpcCAS cas = new GrpcCAS(instanceName, channel, uploader, onExpirations);
  Runnable onExpiration = mock(Runnable.class);
  cas.put(new Blob(uploadContent, digest), onExpiration);
  verify(uploader, times(1))
      .uploadBlob(eq(HashCode.fromString(digest.getHash())), any(Chunker.class));
  assertThat(onExpirations.get(digest)).containsExactly(onExpiration);
  verifyZeroInteractions(onExpiration);
}
 
Example #3
Source Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardSubscriberTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void novelChannelWatcherSubscribes() throws InterruptedException {
  ListMultimap<String, TimedWatchFuture> watchers =
      Multimaps.<String, TimedWatchFuture>synchronizedListMultimap(
          MultimapBuilder.linkedHashKeys().arrayListValues().build());
  RedisShardSubscriber operationSubscriber = createSubscriber(watchers, directExecutor());

  TestClient testClient = new TestClient();
  Thread proceedThread = new Thread(() -> operationSubscriber.proceed(testClient));
  proceedThread.start();
  while (!operationSubscriber.isSubscribed()) {
    MICROSECONDS.sleep(10);
  }

  String novelChannel = "novel-channel";
  TimedWatcher novelWatcher = new UnobservableWatcher();
  operationSubscriber.watch(novelChannel, novelWatcher);
  assertThat(Iterables.getOnlyElement(watchers.get(novelChannel)).getWatcher())
      .isEqualTo(novelWatcher);
  String[] channels = new String[1];
  channels[0] = novelChannel;
  assertThat(testClient.getSubscriptions()).contains(novelChannel);
  operationSubscriber.unsubscribe();
  proceedThread.join();
}
 
Example #4
Source Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardSubscriberTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldResetWatchers() {
  ListMultimap<String, TimedWatchFuture> watchers =
      MultimapBuilder.linkedHashKeys().arrayListValues().build();
  TimedWatcher resetWatcher = new UnobservableWatcher(Instant.EPOCH);

  Instant now = Instant.now();
  assertThat(resetWatcher.isExpiredAt(now)).isTrue();

  String resetChannel = "reset-channel";
  watchers.put(resetChannel, new LidlessTimedWatchFuture(resetWatcher));

  RedisShardSubscriber operationSubscriber = createSubscriber(watchers);
  operationSubscriber.resetWatchers(resetChannel, Instant.MAX);
  assertThat(resetWatcher.isExpiredAt(now)).isFalse();
}
 
Example #5
Source Project: swagger2markup   Author: Swagger2Markup   File: TagUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Groups the operations by tag. The key of the Multimap is the tag name.
 * The value of the Multimap is a PathOperation
 *
 * @param allOperations     all operations
 * @param operationOrdering comparator for operations, for a given tag
 * @return Operations grouped by Tag
 */
public static Multimap<String, SwaggerPathOperation> groupOperationsByTag(List<SwaggerPathOperation> allOperations, Comparator<PathOperation> operationOrdering) {

    Multimap<String, SwaggerPathOperation> operationsGroupedByTag;
    if (operationOrdering == null) {
        operationsGroupedByTag = LinkedHashMultimap.create();
    } else {
        operationsGroupedByTag = MultimapBuilder.linkedHashKeys().treeSetValues(operationOrdering).build();
    }
    for (SwaggerPathOperation operation : allOperations) {
        List<String> tags = operation.getOperation().getTags();

        Validate.notEmpty(tags, "Can't GroupBy.TAGS. Operation '%s' has no tags", operation);
        for (String tag : tags) {
            if (logger.isDebugEnabled()) {
                logger.debug("Added path operation '{}' to tag '{}'", operation, tag);
            }
            operationsGroupedByTag.put(tag, operation);
        }
    }

    return operationsGroupedByTag;
}
 
Example #6
Source Project: baleen   Author: dstl   File: AbstractDiscardWithSameId.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doProcess(final JCas jCas) throws AnalysisEngineProcessException {
  final Multimap<String, T> annotations = MultimapBuilder.hashKeys().arrayListValues().build();

  JCasUtil.select(jCas, clazz).stream().forEach(r -> annotations.put(r.getExternalId(), r));

  final List<T> toDelete = new LinkedList<>();

  annotations.asMap().entrySet().stream()
      .map(Map.Entry::getValue)
      .filter(e -> e.size() > 1)
      // Convert to a list of all annotations, BUT skip (drop) one...
      // that means we'll keep that, and all the other duplicates can get deleted
      .flatMap(e -> e.stream().skip(1))
      // through away all the
      .forEach(toDelete::add);

  removeFromJCasIndex(toDelete);
}
 
Example #7
Source Project: j2objc   Author: google   File: OcniExtractor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds all block comments and associates them with their containing type.
 * This is trickier than you might expect because of inner types.
 */
private static ListMultimap<TreeNode, Comment> findBlockComments(CompilationUnit unit) {
  ListMultimap<TreeNode, Comment> blockComments =
      MultimapBuilder.hashKeys().arrayListValues().build();
  for (Comment comment : unit.getCommentList()) {
    if (!comment.isBlockComment()) {
      continue;
    }
    int commentPos = comment.getStartPosition();
    AbstractTypeDeclaration containingType = null;
    int containingTypePos = -1;
    for (AbstractTypeDeclaration type : unit.getTypes()) {
      int typePos = type.getStartPosition();
      if (typePos < 0) {
        continue;
      }
      int typeEnd = typePos + type.getLength();
      if (commentPos > typePos && commentPos < typeEnd && typePos > containingTypePos) {
        containingType = type;
        containingTypePos = typePos;
      }
    }
    blockComments.put(containingType != null ? containingType : unit, comment);
  }
  return blockComments;
}
 
Example #8
Source Project: glowroot   Author: glowroot   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 #9
Source Project: js-dossier   Author: jleyba   File: SymbolTable.java    License: Apache License 2.0 6 votes vote down vote up
private SymbolTable(@Nullable SymbolTable parent, @Nullable Node root) {
  checkArgument(
      (parent == null) == (root == null),
      "symbol table must have a root node IFF it is not global");

  this.parent = parent;
  this.root = root;

  if (this.parent == null) {
    modulesByPath = new HashMap<>();
    modulesById = new HashMap<>();
    modulesByRoot = new HashMap<>();
    closureModulesById = new HashMap<>();
    regions = MultimapBuilder.hashKeys().arrayListValues().build();
  } else {
    modulesByPath = ImmutableMap.of();
    modulesById = ImmutableMap.of();
    modulesByRoot = ImmutableMap.of();
    closureModulesById = ImmutableMap.of();
    regions = ImmutableListMultimap.of();
  }
}
 
Example #10
Source Project: buck   Author: facebook   File: VFSOverlay.java    License: Apache License 2.0 6 votes vote down vote up
@JsonProperty("roots")
private ImmutableList<VirtualDirectory> computeRoots() {
  Multimap<Path, Pair<Path, Path>> byParent = MultimapBuilder.hashKeys().hashSetValues().build();
  overlays.forEach(
      (virtual, real) -> {
        byParent.put(virtual.getParent(), new Pair<>(virtual.getFileName(), real));
      });
  return byParent.asMap().entrySet().stream()
      .map(
          e ->
              new VirtualDirectory(
                  e.getKey(),
                  e.getValue().stream()
                      .map(x -> new VirtualFile(x.getFirst(), x.getSecond()))
                      .collect(ImmutableList.toImmutableList())))
      .collect(ImmutableList.toImmutableList());
}
 
Example #11
Source Project: BlueMap   Author: BlueMap-Minecraft   File: ResourcePack.java    License: MIT License 5 votes vote down vote up
public ResourcePack() {
	blockStateResources = new HashMap<>();
	blockModelResources = new HashMap<>();
	textures = new TextureGallery();
	foliageMap = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
	foliageMap.setRGB(0, 0, 0xFF00FF00);
	grassMap = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
	grassMap.setRGB(0, 0, 0xFF00FF00);
	blockColorCalculator = new BlockColorCalculator(foliageMap, grassMap);
	configs = MultimapBuilder.hashKeys().arrayListValues().build();
}
 
Example #12
Source Project: BlueMap   Author: BlueMap-Minecraft   File: RenderManager.java    License: MIT License 5 votes vote down vote up
public void writeState(DataOutputStream out) throws IOException {
	//prepare renderTickets
	ListMultimap<MapType, Vector2i> tileMap = MultimapBuilder.hashKeys().arrayListValues().<MapType, Vector2i>build();
	synchronized (renderTickets) {
		for (RenderTicket ticket : renderTickets) {
			tileMap.put(ticket.getMapType(), ticket.getTile());
		}	
	}
	
	//write renderTickets
	Set<MapType> maps = tileMap.keySet();
	out.writeInt(maps.size());
	for (MapType map : maps) {
		List<Vector2i> tiles = tileMap.get(map);
		
		out.writeUTF(map.getId());
		out.writeInt(tiles.size());
		for (Vector2i tile : tiles) {
			out.writeInt(tile.getX());
			out.writeInt(tile.getY());
		}
	}
	
	//write tasks
	synchronized (renderTasks) {
		out.writeInt(renderTasks.size());
		for (RenderTask task : renderTasks) {
			task.write(out);
		}
	}
}
 
Example #13
Source Project: bcm-android   Author: bcmapp   File: PaymentChannelV2ClientState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.NEW);
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.NEW, State.SAVE_STATE_IN_WALLET);
    result.put(State.SAVE_STATE_IN_WALLET, State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
    result.put(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, State.READY);
    result.put(State.READY, State.EXPIRED);
    result.put(State.READY, State.CLOSED);
    return result;
}
 
Example #14
Source Project: bcm-android   Author: bcmapp   File: PaymentChannelV2ServerState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.UNINITIALISED, State.WAITING_FOR_MULTISIG_CONTRACT);
    result.put(State.WAITING_FOR_MULTISIG_CONTRACT, State.WAITING_FOR_MULTISIG_ACCEPTANCE);
    result.put(State.WAITING_FOR_MULTISIG_ACCEPTANCE, State.READY);
    result.put(State.READY, State.CLOSING);
    result.put(State.CLOSING, State.CLOSED);
    for (State state : State.values()) {
        result.put(state, State.ERROR);
    }
    return result;
}
 
Example #15
Source Project: bcm-android   Author: bcmapp   File: PaymentChannelV1ClientState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.NEW);
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.NEW, State.INITIATED);
    result.put(State.INITIATED, State.WAITING_FOR_SIGNED_REFUND);
    result.put(State.WAITING_FOR_SIGNED_REFUND, State.SAVE_STATE_IN_WALLET);
    result.put(State.SAVE_STATE_IN_WALLET, State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
    result.put(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, State.READY);
    result.put(State.READY, State.EXPIRED);
    result.put(State.READY, State.CLOSED);
    return result;
}
 
Example #16
Source Project: raptor   Author: geekshop   File: ProfileLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a multimap whose keys are base directories and whose values are potential locations of
 * wire profile files.
 */
Multimap<Path, String> pathsToAttempt(Set<Location> protoLocations) {
  Multimap<Path, String> result = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build();
  for (Location location : protoLocations) {
    pathsToAttempt(result, location);
  }
  return result;
}
 
Example #17
Source Project: green_android   Author: Blockstream   File: PaymentChannelV2ClientState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.NEW);
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.NEW, State.SAVE_STATE_IN_WALLET);
    result.put(State.SAVE_STATE_IN_WALLET, State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
    result.put(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, State.READY);
    result.put(State.READY, State.EXPIRED);
    result.put(State.READY, State.CLOSED);
    return result;
}
 
Example #18
Source Project: green_android   Author: Blockstream   File: PaymentChannelV2ServerState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.UNINITIALISED, State.WAITING_FOR_MULTISIG_CONTRACT);
    result.put(State.WAITING_FOR_MULTISIG_CONTRACT, State.WAITING_FOR_MULTISIG_ACCEPTANCE);
    result.put(State.WAITING_FOR_MULTISIG_ACCEPTANCE, State.READY);
    result.put(State.READY, State.CLOSING);
    result.put(State.CLOSING, State.CLOSED);
    for (State state : State.values()) {
        result.put(state, State.ERROR);
    }
    return result;
}
 
Example #19
Source Project: green_android   Author: Blockstream   File: PaymentChannelV1ClientState.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Multimap<State, State> getStateTransitions() {
    Multimap<State, State> result = MultimapBuilder.enumKeys(State.class).arrayListValues().build();
    result.put(State.UNINITIALISED, State.NEW);
    result.put(State.UNINITIALISED, State.READY);
    result.put(State.NEW, State.INITIATED);
    result.put(State.INITIATED, State.WAITING_FOR_SIGNED_REFUND);
    result.put(State.WAITING_FOR_SIGNED_REFUND, State.SAVE_STATE_IN_WALLET);
    result.put(State.SAVE_STATE_IN_WALLET, State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
    result.put(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER, State.READY);
    result.put(State.READY, State.EXPIRED);
    result.put(State.READY, State.CLOSED);
    return result;
}
 
Example #20
Source Project: bundletool   Author: google   File: CollectorUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@code Collector} accumulating entries into an {@code ImmutableListMultimap}.
 *
 * <p>The keys of the entries are the result of applying the provided key mapping function while
 * the values are generated by applying the value mapping function and accumulated in the
 * encounter order of the stream.
 */
public static <T, K extends Comparable<K>, V>
    Collector<T, ?, ImmutableListMultimap<K, V>> groupingBySortedKeys(
        Function<? super T, ? extends K> keyFunction,
        Function<? super T, ? extends V> valueFunction) {
  return Collectors.collectingAndThen(
      Multimaps.toMultimap(
          keyFunction, valueFunction, MultimapBuilder.treeKeys().arrayListValues()::<K, V>build),
      ImmutableListMultimap::copyOf);
}
 
Example #21
Source Project: Elasticsearch   Author: baidu   File: SearchContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Schedule the release of a resource. The time when {@link Releasable#close()} will be called on this object
 * is function of the provided {@link Lifetime}.
 */
public void addReleasable(Releasable releasable, Lifetime lifetime) {
    if (clearables == null) {
        clearables = MultimapBuilder.enumKeys(Lifetime.class).arrayListValues().build();
    }
    clearables.put(lifetime, releasable);
}
 
Example #22
Source Project: exonum-java-binding   Author: exonum   File: TestKit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a shallow copy of this TestKit builder.
 *
 * <p>Note that the remaining mutable state are {@linkplain TimeProvider time providers}.
 */
Builder shallowCopy() {
  Builder builder = new Builder()
      .withNodeType(nodeType)
      .withValidators(validatorCount)
      .withArtifactsDirectory(artifactsDirectory);
  builder.timeServiceSpec = timeServiceSpec;
  builder.services = MultimapBuilder.hashKeys().arrayListValues().build(services);
  builder.serviceArtifactFilenames = new HashMap<>(serviceArtifactFilenames);
  return builder;
}
 
Example #23
Source Project: dremio-oss   Author: dremio   File: TestDependencyGraph.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadFromStore() throws Exception {
  final DependenciesStore dependenciesStore = Mockito.mock(DependenciesStore.class);

  final DependencyGraph graph = new DependencyGraph(dependenciesStore);

  // let's add some dependencies to the store
  // Map<Dependant, List<Parent>>
  final Multimap<String, String> dependencyMap = MultimapBuilder.hashKeys().arrayListValues().build();
  // pds1 > raw1 > agg1
  dependencyMap.put("raw1", "pds1");
  dependencyMap.put("agg1", "raw1");
  // pds2 > raw2 > agg2
  dependencyMap.put("raw2", "pds2");
  dependencyMap.put("agg2", "raw2");
  // raw2 > agg3
  dependencyMap.put("agg3", "raw2");
  // raw1, raw2 > vds-raw > vds-agg1
  dependencyMap.putAll("vds-raw", Lists.newArrayList("raw1", "raw2"));
  dependencyMap.put("vds-agg1", "vds-raw");
  // agg1, agg2 > vds-agg2
  dependencyMap.putAll("vds-agg2", Lists.newArrayList("agg1", "agg2"));

  Mockito.when(dependenciesStore.getAll()).thenReturn(storeDependencies(dependencyMap).entrySet());
  graph.loadFromStore();

  for (String dependant : dependencyMap.keySet()) {
    // we only store subgraphs of reflections
    for (String parent : dependencyMap.get(dependant)) {
      assertTrue(String.format("%s > %s", parent, dependant), isPredecessor(graph, parent, dependant));
      if (dependencyByName.get(parent).getType() == DependencyType.REFLECTION) {
        assertTrue(String.format("%s < %s", dependant, parent), isSuccessor(graph, parent, dependant));
      }
    }
  }
}
 
Example #24
Source Project: bazel-buildfarm   Author: bazelbuild   File: ContentAddressableStorages.java    License: Apache License 2.0 5 votes vote down vote up
public static ContentAddressableStorage createGrpcCAS(GrpcCASConfig config) {
  Channel channel = createChannel(config.getTarget());
  ByteStreamUploader byteStreamUploader =
      new ByteStreamUploader("", channel, null, 300, NO_RETRIES);
  ListMultimap<Digest, Runnable> onExpirations =
      synchronizedListMultimap(MultimapBuilder.hashKeys().arrayListValues().build());

  return new GrpcCAS(config.getInstanceName(), channel, byteStreamUploader, onExpirations);
}
 
Example #25
Source Project: bazel-buildfarm   Author: bazelbuild   File: MemoryInstance.java    License: Apache License 2.0 5 votes vote down vote up
public MemoryInstance(String name, DigestUtil digestUtil, MemoryInstanceConfig config) {
  this(
      name,
      digestUtil,
      config,
      ContentAddressableStorages.create(config.getCasConfig()),
      /* watchers=*/ synchronizedSetMultimap(
          MultimapBuilder.hashKeys().hashSetValues(/* expectedValuesPerKey=*/ 1).build()),
      /* watcherExecutor=*/ newCachedThreadPool(),
      new OutstandingOperations(),
      /* workers=*/ Lists.newArrayList(),
      /* requeuers=*/ Maps.newConcurrentMap(),
      /* operationTimeoutDelays=*/ Maps.newConcurrentMap());
}
 
Example #26
Source Project: bazel-buildfarm   Author: bazelbuild   File: GrpcCASTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  // Use a mutable service registry for later registering the service impl for each test case.
  fakeServer =
      InProcessServerBuilder.forName(fakeServerName)
          .fallbackHandlerRegistry(serviceRegistry)
          .directExecutor()
          .build()
          .start();

  onExpirations = MultimapBuilder.hashKeys().arrayListValues().build();
}
 
Example #27
Source Project: bazel-buildfarm   Author: bazelbuild   File: MemoryInstanceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  outstandingOperations = new MemoryInstance.OutstandingOperations();
  watchers =
      synchronizedSetMultimap(
          MultimapBuilder.hashKeys().hashSetValues(/* expectedValuesPerKey=*/ 1).build());
  watcherService = newDirectExecutorService();
  MemoryInstanceConfig memoryInstanceConfig =
      MemoryInstanceConfig.newBuilder()
          .setListOperationsDefaultPageSize(1024)
          .setListOperationsMaxPageSize(16384)
          .setTreeDefaultPageSize(1024)
          .setTreeMaxPageSize(16384)
          .setOperationPollTimeout(Durations.fromSeconds(10))
          .setOperationCompletedDelay(Durations.fromSeconds(10))
          .setDefaultActionTimeout(Durations.fromSeconds(600))
          .setMaximumActionTimeout(MAXIMUM_ACTION_TIMEOUT)
          .setActionCacheConfig(
              ActionCacheConfig.newBuilder()
                  .setDelegateCas(DelegateCASConfig.getDefaultInstance())
                  .build())
          .build();

  storage = Maps.newHashMap();
  workers = Lists.newArrayList();
  requeuers = Maps.newHashMap();
  operationTimeoutDelays = Maps.newHashMap();
  instance =
      new MemoryInstance(
          "memory",
          DIGEST_UTIL,
          memoryInstanceConfig,
          casMapDecorator(storage),
          watchers,
          watcherService,
          outstandingOperations,
          workers,
          requeuers,
          operationTimeoutDelays);
}
 
Example #28
Source Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardSubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void watchedOperationChannelsReflectsWatchers() {
  ListMultimap<String, TimedWatchFuture> watchers =
      MultimapBuilder.linkedHashKeys().arrayListValues().build();
  RedisShardSubscriber operationSubscriber = createSubscriber(watchers);
  assertThat(operationSubscriber.watchedOperationChannels()).isEmpty();
  String addedChannel = "added-channel";
  watchers.put(addedChannel, null);
  assertThat(operationSubscriber.watchedOperationChannels()).containsExactly(addedChannel);
  watchers.removeAll(addedChannel);
  assertThat(operationSubscriber.watchedOperationChannels()).isEmpty();
}
 
Example #29
Source Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardSubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void expiredWatchedOperationChannelsReflectsWatchers() {
  ListMultimap<String, TimedWatchFuture> watchers =
      MultimapBuilder.linkedHashKeys().arrayListValues().build();
  RedisShardSubscriber operationSubscriber = createSubscriber(watchers);

  TimedWatcher unexpiredWatcher = new UnobservableWatcher(Instant.MAX);
  TimedWatcher expiredWatcher = new UnobservableWatcher(Instant.EPOCH);
  Instant now = Instant.now();
  // EPOCH < now < MAX

  assertThat(operationSubscriber.expiredWatchedOperationChannels(now)).isEmpty();

  String unexpiredChannel = "channel-with-unexpired-watcher";
  watchers.put(unexpiredChannel, new LidlessTimedWatchFuture(unexpiredWatcher));
  assertThat(operationSubscriber.expiredWatchedOperationChannels(now)).isEmpty();

  String expiredChannel = "channel-with-expired-watcher";
  watchers.put(expiredChannel, new LidlessTimedWatchFuture(expiredWatcher));
  assertThat(operationSubscriber.expiredWatchedOperationChannels(now))
      .containsExactly(expiredChannel);

  String mixedChannel = "channel-with-some-expired-watchers";
  watchers.put(mixedChannel, new LidlessTimedWatchFuture(unexpiredWatcher));
  watchers.put(mixedChannel, new LidlessTimedWatchFuture(expiredWatcher));
  watchers.put(mixedChannel, new LidlessTimedWatchFuture(expiredWatcher));
  watchers.put(mixedChannel, new LidlessTimedWatchFuture(unexpiredWatcher));
  assertThat(operationSubscriber.expiredWatchedOperationChannels(now))
      .containsExactly(expiredChannel, mixedChannel);

  watchers.removeAll(expiredChannel);
  assertThat(operationSubscriber.expiredWatchedOperationChannels(now))
      .containsExactly(mixedChannel);

  watchers.removeAll(mixedChannel);
  assertThat(operationSubscriber.expiredWatchedOperationChannels(now)).isEmpty();
}
 
Example #30
Source Project: bazel-buildfarm   Author: bazelbuild   File: RedisShardSubscriberTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void existingChannelWatcherSuppressesSubscription() {
  ListMultimap<String, TimedWatchFuture> watchers =
      MultimapBuilder.linkedHashKeys().arrayListValues().build();
  RedisShardSubscriber operationSubscriber = createSubscriber(watchers, directExecutor());
  String existingChannel = "existing-channel";
  TimedWatcher existingWatcher = new UnobservableWatcher();
  watchers.put(existingChannel, new LidlessTimedWatchFuture(existingWatcher));
  TimedWatcher novelWatcher = new UnobservableWatcher();
  operationSubscriber.watch(existingChannel, novelWatcher);
  assertThat(watchers.get(existingChannel).size()).isEqualTo(2);
}