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 File: RedisShardSubscriberTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@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 #2
Source File: ClasspathCache.java From glowroot with Apache License 2.0 | 6 votes |
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 #3
Source File: SymbolTable.java From js-dossier with Apache License 2.0 | 6 votes |
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 #4
Source File: VFSOverlay.java From buck with Apache License 2.0 | 6 votes |
@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 #5
Source File: OcniExtractor.java From j2objc with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: RedisShardBackplane.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
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 #7
Source File: TagUtils.java From swagger2markup with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: GrpcCASTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@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 #9
Source File: RedisShardSubscriberTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@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 #10
Source File: AbstractDiscardWithSameId.java From baleen with Apache License 2.0 | 6 votes |
@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 #11
Source File: PaymentChannelV2ClientState.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@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 #12
Source File: RedisUtils.java From geowave with Apache License 2.0 | 5 votes |
public static Iterator<GeoWaveMetadata> groupByIds(final Iterable<GeoWaveMetadata> result) { final ListMultimap<ByteArray, GeoWaveMetadata> multimap = MultimapBuilder.hashKeys().arrayListValues().build(); result.forEach( r -> multimap.put(new ByteArray(Bytes.concat(r.getPrimaryId(), r.getSecondaryId())), r)); return multimap.values().iterator(); }
Example #13
Source File: PaymentChannelV1ClientState.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@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 #14
Source File: ResourcePack.java From BlueMap with MIT License | 5 votes |
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 #15
Source File: BrooklynJacksonSerializerTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testMultiMapSerialization() throws Exception { Multimap<String, Integer> m = MultimapBuilder.hashKeys().arrayListValues().build(); m.put("bob", 24); m.put("bob", 25); String result = checkSerializesAs(m, null); log.info("multimap serialized as: " + result); Assert.assertFalse(result.contains("error"), "Shouldn't have had an error, instead got: "+result); Assert.assertEquals(Strings.collapseWhitespace(result, ""), "{\"bob\":[24,25]}"); }
Example #16
Source File: MultimapSerializerTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testSerializeStringKey() throws Exception { Multimap<String, Integer> map = MultimapBuilder.hashKeys().arrayListValues().build(); map.put("a", 1); map.put("a", 2); map.put("a", 3); String json = mapper.writer().writeValueAsString(map); assertEquals(json, "{\"a\":[1,2,3]}"); }
Example #17
Source File: MultimapSerializerTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testSerializeEntityKey() throws Exception { Entity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)); Multimap<Entity, Integer> map = MultimapBuilder.hashKeys().arrayListValues().build(); map.put(entity, 1); map.put(entity, 2); map.put(entity, 3); String json = mapper.writer().writeValueAsString(map); assertEquals(json, "{\"BasicEntityImpl{id=" + entity.getId() + "}" + "\":[1,2,3]}"); }
Example #18
Source File: TypeDeclarationGenerator.java From j2objc with Apache License 2.0 | 5 votes |
/** * Print method declarations with #pragma mark lines documenting their scope. */ @Override protected void printInnerDeclarations() { // Everything is public in interfaces. if (isInterfaceType() || typeNode.hasPrivateDeclaration()) { super.printInnerDeclarations(); return; } ListMultimap<DeclarationCategory, BodyDeclaration> categorizedDecls = MultimapBuilder.hashKeys().arrayListValues().build(); for (BodyDeclaration innerDecl : getInnerDeclarations()) { categorizedDecls.put(DeclarationCategory.categorize(innerDecl), innerDecl); } // Emit the categorized declarations using the declaration order of the category values. for (DeclarationCategory category : DeclarationCategory.values()) { List<BodyDeclaration> declarations = categorizedDecls.get(category); if (declarations.isEmpty()) { continue; } // Extract MethodDeclaration nodes so that they can be sorted. List<MethodDeclaration> methods = Lists.newArrayList(); for (Iterator<BodyDeclaration> iter = declarations.iterator(); iter.hasNext(); ) { BodyDeclaration decl = iter.next(); if (decl instanceof MethodDeclaration) { methods.add((MethodDeclaration) decl); iter.remove(); } } Collections.sort(methods, METHOD_DECL_ORDER); newline(); println(category.header); printDeclarations(methods); printDeclarations(declarations); } }
Example #19
Source File: TestSummary.java From bazel with Apache License 2.0 | 5 votes |
void mergeFrom(TestSummary existingSummary) { // Yuck, manually fill in fields. summary.shardRunStatuses = MultimapBuilder.hashKeys().arrayListValues().build(existingSummary.shardRunStatuses); summary.firstStartTimeMillis = existingSummary.firstStartTimeMillis; summary.lastStopTimeMillis = existingSummary.lastStopTimeMillis; summary.totalRunDurationMillis = existingSummary.totalRunDurationMillis; setTarget(existingSummary.target); setConfiguration(existingSummary.configuration); setStatus(existingSummary.status); addCoverageFiles(existingSummary.coverageFiles); addPassedLogs(existingSummary.passedLogs); addFailedLogs(existingSummary.failedLogs); summary.totalTestCases += existingSummary.totalTestCases; summary.totalUnknownTestCases += existingSummary.totalUnknownTestCases; if (existingSummary.failedTestCasesStatus != null) { addFailedTestCases( existingSummary.getFailedTestCases(), existingSummary.getFailedTestCasesStatus()); } addTestTimes(existingSummary.testTimes); addWarnings(existingSummary.warnings); setActionRan(existingSummary.actionRan); setNumCached(existingSummary.numCached); setRanRemotely(existingSummary.ranRemotely); setWasUnreportedWrongSize(existingSummary.wasUnreportedWrongSize); }
Example #20
Source File: CommandInterface.java From drftpd with GNU General Public License v2.0 | 5 votes |
public synchronized void initialize(String method, String pluginName, StandardCommandManager cManager) { Multimap<Integer, HookContainer> postHooks = MultimapBuilder.treeKeys().linkedListValues().build(); Multimap<Integer, HookContainer> preHooks = MultimapBuilder.treeKeys().linkedListValues().build(); Set<Method> hooksMethods = GlobalContext.getHooksMethods(); // TODO [DONE] @k2r Plug hooks logger.debug("[{}:{}] Looking for hooks to attach here", pluginName, method); try { for (Method annotatedMethod : hooksMethods) { Class<?> declaringClass = annotatedMethod.getDeclaringClass(); CommandHook annotation = annotatedMethod.getAnnotation(CommandHook.class); int priority = annotation.priority(); List<String> commands = Arrays.asList(annotation.commands()); // boolean handleClass = commands.stream().filter(c -> method.matches(c)).collect(Collectors.toList()).size() > 0; boolean handleClass = commands.contains(method) || commands.contains("*"); if (!handleClass) continue; Object hookClass = declaringClass.getConstructor().newInstance(); HookType type = annotation.type(); if (type.equals(HookType.PRE)) { preHooks.put(priority, new HookContainer(annotatedMethod, hookClass)); } else { postHooks.put(priority, new HookContainer(annotatedMethod, hookClass)); } } } catch (Exception e) { logger.error("Failed to load plugins for {} extension point 'PreHook', possibly the {} extension point definition has changed in the plugin.xml", pluginName, pluginName, e); } logger.debug("[{}:{}] Loaded [{}] prehooks and [{}] posthooks", pluginName, method, preHooks.size(), postHooks.size()); _preHooks = preHooks; _postHooks = postHooks; }
Example #21
Source File: AppEngineRuleTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testOfyEntities_uniqueKinds() { try (ScanResult scanResult = new ClassGraph() .enableAnnotationInfo() .ignoreClassVisibility() .whitelistPackages("google.registry") .scan()) { Multimap<String, Class<?>> kindToEntityMultiMap = scanResult.getClassesWithAnnotation(Entity.class.getName()).stream() .filter(clazz -> !clazz.getName().equals(TestObject.class.getName())) .map(clazz -> clazz.loadClass()) .collect( Multimaps.toMultimap( Key::getKind, clazz -> clazz, MultimapBuilder.hashKeys().linkedListValues()::build)); Map<String, Collection<Class<?>>> conflictingKinds = kindToEntityMultiMap.asMap().entrySet().stream() .filter(e -> e.getValue().size() > 1) .collect(entriesToImmutableMap()); assertWithMessage( "Conflicting Ofy kinds found. Tests will break if they are registered with " + " AppEngineRule in the same test executor.") .that(conflictingKinds) .isEmpty(); } }
Example #22
Source File: RedisUtils.java From geowave with Apache License 2.0 | 5 votes |
public static Iterator<ScoredEntry<GeoWaveRedisPersistedRow>> groupByRow( final Iterator<ScoredEntry<GeoWaveRedisPersistedRow>> result, final boolean sortByTime) { final ListMultimap<Pair<Double, ByteArray>, ScoredEntry<GeoWaveRedisPersistedRow>> multimap = MultimapBuilder.hashKeys().arrayListValues().build(); result.forEachRemaining( r -> multimap.put(Pair.of(r.getScore(), new ByteArray(r.getValue().getDataId())), r)); if (sortByTime) { multimap.asMap().forEach( (k, v) -> Collections.sort( (List<ScoredEntry<GeoWaveRedisPersistedRow>>) v, TIMESTAMP_COMPARATOR)); } return multimap.values().iterator(); }
Example #23
Source File: FlowContext.java From nomulus with Apache License 2.0 | 5 votes |
/** * Returns a multimap mapping each exception imported in test files for this flow to the set of * filenames for files that import that exception. */ private SetMultimap<ErrorCase, String> getImportExceptions() throws IOException { ImmutableMultimap.Builder<String, ErrorCase> builder = new ImmutableMultimap.Builder<>(); for (String testFileName : testFilenames) { builder.putAll(testFileName, getImportExceptionsFromFile(testFileName)); } // Invert the mapping so that later we can easily map exceptions to where they were imported. return MultimapBuilder.hashKeys().hashSetValues().build(builder.build().inverse()); }
Example #24
Source File: CommandInterface.java From drftpd with GNU General Public License v2.0 | 5 votes |
public synchronized void initialize(String method, String pluginName, StandardCommandManager cManager) { Multimap<Integer, HookContainer> postHooks = MultimapBuilder.treeKeys().linkedListValues().build(); Multimap<Integer, HookContainer> preHooks = MultimapBuilder.treeKeys().linkedListValues().build(); Set<Method> hooksMethods = GlobalContext.getHooksMethods(); // TODO [DONE] @k2r Plug hooks logger.debug("[{}:{}] Looking for hooks to attach here", pluginName, method); try { for (Method annotatedMethod : hooksMethods) { Class<?> declaringClass = annotatedMethod.getDeclaringClass(); CommandHook annotation = annotatedMethod.getAnnotation(CommandHook.class); int priority = annotation.priority(); List<String> commands = Arrays.asList(annotation.commands()); // boolean handleClass = commands.stream().filter(c -> method.matches(c)).collect(Collectors.toList()).size() > 0; boolean handleClass = commands.contains(method) || commands.contains("*"); if (!handleClass) continue; Object hookClass = declaringClass.getConstructor().newInstance(); HookType type = annotation.type(); if (type.equals(HookType.PRE)) { preHooks.put(priority, new HookContainer(annotatedMethod, hookClass)); } else { postHooks.put(priority, new HookContainer(annotatedMethod, hookClass)); } } } catch (Exception e) { logger.error("Failed to load plugins for {} extension point 'PreHook', possibly the {} extension point definition has changed in the plugin.xml", pluginName, pluginName, e); } logger.debug("[{}:{}] Loaded [{}] prehooks and [{}] posthooks", pluginName, method, preHooks.size(), postHooks.size()); _preHooks = preHooks; _postHooks = postHooks; }
Example #25
Source File: TurbineElements.java From turbine with Apache License 2.0 | 5 votes |
@Override public List<? extends Element> getAllMembers(TypeElement type) { ClassSymbol s = (ClassSymbol) asSymbol(type); PackageSymbol from = packageSymbol(s); // keep track of processed methods grouped by their names, to handle overrides more efficiently Multimap<String, TurbineExecutableElement> methods = MultimapBuilder.linkedHashKeys().linkedHashSetValues().build(); // collect all members of each transitive supertype of the input ImmutableList.Builder<Element> results = ImmutableList.builder(); for (ClassSymbol superType : factory.cha().transitiveSupertypes(s)) { // Most of JSR-269 is implemented on top of turbine's model, instead of the Element and // TypeMirror wrappers. We don't do that here because we need most of the Elements returned // by getEnclosedElements anyways, and the work below benefits from some of the caching done // by TurbineElement. for (Element el : factory.typeElement(superType).getEnclosedElements()) { Symbol sym = asSymbol(el); switch (sym.symKind()) { case METHOD: TurbineExecutableElement m = (TurbineExecutableElement) el; if (shouldAdd(s, from, methods, m)) { methods.put(m.info().name(), m); results.add(el); } break; case FIELD: if (shouldAdd(s, from, (TurbineFieldElement) el)) { results.add(el); } break; default: results.add(el); } } } return results.build(); }
Example #26
Source File: WEBUI_SalesOrder_Apply_Availability_Row.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 5 votes |
private Multimap<PurchaseRow, PurchaseRow> extractLineRow2availabilityRows() { final PurchaseView view = getView(); final ListMultimap<PurchaseRow, PurchaseRow> lineRow2AvailabilityRows = getSelectedRowIds().stream() .map(PurchaseRowId::fromDocumentId) // map to PurchaseRowIds .filter(PurchaseRowId::isAvailabilityRowId) .filter(availabilityRowId -> availabilityRowId.getAvailabilityType().equals(Type.AVAILABLE)) .map(availabilityRowId -> ImmutablePair.of( // map to pair (availabilityRowId, availabilityRow) availabilityRowId, view.getById(availabilityRowId.toDocumentId()))) .filter(availabilityRowId2row -> isPositive(availabilityRowId2row.getRight().getQtyToPurchase())) .map(availabilityRowId2row -> ImmutablePair.of( // map to pair (lineRow, availabilityRow) view.getById(availabilityRowId2row.getLeft().toLineRowId().toDocumentId()), availabilityRowId2row.getRight())) .filter(lineRow2availabilityRow -> !lineRow2availabilityRow.getLeft().isProcessed()) .collect(Multimaps.toMultimap( IPair::getLeft, IPair::getRight, MultimapBuilder.hashKeys().arrayListValues()::build)); return ImmutableMultimap.copyOf(lineRow2AvailabilityRows); }
Example #27
Source File: RedisShardSubscriberTest.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
@Test public void invalidOperationChangeIsIgnored() { ListMultimap<String, TimedWatchFuture> watchers = MultimapBuilder.linkedHashKeys().arrayListValues().build(); RedisShardSubscriber operationSubscriber = createSubscriber(watchers, directExecutor()); operationSubscriber.onMessage("invalid-operation-change", "not-json!#?"); }
Example #28
Source File: RedisShardSubscriberTest.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
@Test public void unsetTypeOperationChangeIsIgnored() { ListMultimap<String, TimedWatchFuture> watchers = MultimapBuilder.linkedHashKeys().arrayListValues().build(); RedisShardSubscriber operationSubscriber = createSubscriber(watchers, directExecutor()); operationSubscriber.onOperationChange( "unset-type-operation", OperationChange.getDefaultInstance()); }
Example #29
Source File: ApplePackageDescription.java From buck with Apache License 2.0 | 5 votes |
/** * Get the correct package configuration based on the platform flavors of this build target. * * <p>Validates that all named platforms yields the identical package config. * * @return If found, a package config for this target. * @throws HumanReadableException if there are multiple possible package configs. */ private Optional<ImmutableApplePackageConfigAndPlatformInfo> getApplePackageConfig( BuildTarget target, Optional<Flavor> defaultPlatform, ActionGraphBuilder graphBuilder) { FlavorDomain<UnresolvedAppleCxxPlatform> appleCxxPlatformFlavorDomain = getAppleCxxPlatformsFlavorDomain(target.getTargetConfiguration()); Set<Flavor> platformFlavors = getPlatformFlavorsOrDefault(target, defaultPlatform, appleCxxPlatformFlavorDomain); // Ensure that different platforms generate the same config. // The value of this map is just for error reporting. Multimap<Optional<ImmutableApplePackageConfigAndPlatformInfo>, Flavor> packageConfigs = MultimapBuilder.hashKeys().arrayListValues().build(); for (Flavor flavor : platformFlavors) { AppleCxxPlatform platform = appleCxxPlatformFlavorDomain.getValue(flavor).resolve(graphBuilder); Optional<AppleConfig.ApplePackageConfig> packageConfig = config.getPackageConfigForPlatform(platform.getAppleSdk().getApplePlatform()); packageConfigs.put( packageConfig.map( applePackageConfig -> ImmutableApplePackageConfigAndPlatformInfo.of(applePackageConfig, platform)), flavor); } if (packageConfigs.isEmpty()) { return Optional.empty(); } else if (packageConfigs.keySet().size() == 1) { return Iterables.getOnlyElement(packageConfigs.keySet()); } else { throw new HumanReadableException( "In target %s: Multi-architecture package has different package configs for targets: %s", target.getFullyQualifiedName(), packageConfigs.asMap().values()); } }
Example #30
Source File: PaymentChannelV2ServerState.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@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; }