类com.google.common.collect.ListMultimap源码实例Demo

下面列出了怎么用com.google.common.collect.ListMultimap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: grpc-nebula-java   文件: NettyServerStreamTest.java
@Test
public void writeHeadersShouldSendHeaders() throws Exception {
  Metadata headers = new Metadata();
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(Utils.convertServerHeaders(headers));

  stream().writeHeaders(headers);

  ArgumentCaptor<SendResponseHeadersCommand> sendHeadersCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(sendHeadersCap.capture(), eq(true));
  SendResponseHeadersCommand sendHeaders = sendHeadersCap.getValue();
  assertThat(sendHeaders.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(sendHeaders.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(sendHeaders.endOfStream()).isFalse();
}
 
源代码2 项目: trainbenchmark   文件: NewQueriesTest.java
@Test
public void routeReachabilityTest() throws Exception {
	// Arrange
	final String workload = "NewQueriesTest";
	final String modelFilename = "railway-repair-" + largeSize;
	final List<RailwayOperation> operations = ImmutableList.of(//
		RailwayOperation.ROUTEREACHABILITY //
	);
	final BenchmarkConfigBase bcb = bcbbTransformation.setModelFilename(modelFilename).setOperations(operations)
		.setWorkload(workload).createConfigBase();

	// Act
	final BenchmarkResult result = runTest(bcb);

	// Assert
	final ListMultimap<RailwayQuery, Integer> allMatches = result.getLastRunResult().getMatches();
	collector.checkThat(allMatches.get(RailwayQuery.ROUTEREACHABILITY).get(0), Matchers.equalTo(26));
}
 
源代码3 项目: Strata   文件: FpmlDocument.java
private ListMultimap<String, StandardId> parseAllTradeIds(XmlElement tradeHeaderEl) {
  // look through each partyTradeIdentifier
  ListMultimap<String, StandardId> allIds = ArrayListMultimap.create();
  List<XmlElement> partyTradeIdentifierEls = tradeHeaderEl.getChildren("partyTradeIdentifier");
  for (XmlElement partyTradeIdentifierEl : partyTradeIdentifierEls) {
    Optional<XmlElement> partyRefOptEl = partyTradeIdentifierEl.findChild("partyReference");
    if (partyRefOptEl.isPresent() && partyRefOptEl.get().findAttribute(HREF).isPresent()) {
      String partyHref = partyRefOptEl.get().findAttribute(HREF).get();
      // try to find a tradeId, either in versionedTradeId or as a direct child
      Optional<XmlElement> vtradeIdOptEl = partyTradeIdentifierEl.findChild("versionedTradeId");
      Optional<XmlElement> tradeIdOptEl = vtradeIdOptEl
          .map(vt -> Optional.of(vt.getChild("tradeId")))
          .orElse(partyTradeIdentifierEl.findChild("tradeId"));
      if (tradeIdOptEl.isPresent() && tradeIdOptEl.get().findAttribute("tradeIdScheme").isPresent()) {
        XmlElement tradeIdEl = tradeIdOptEl.get();
        String scheme = tradeIdEl.getAttribute("tradeIdScheme");
        // ignore if there is an empty scheme or value
        if (!scheme.isEmpty() && !tradeIdEl.getContent().isEmpty()) {
          allIds.put(partyHref, StandardId.of(StandardId.encodeScheme(scheme), tradeIdEl.getContent()));
        }
      }
    }
  }
  return allIds;
}
 
@Test
public void oauthClassesNotInClassPath() throws Exception {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  when(credentials.getRequestMetadata(eq(expectedUri))).thenReturn(Multimaps.asMap(values));

  assertNull(GoogleAuthLibraryCallCredentials.createJwtHelperOrNull(null));
  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials, null);
  callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);

  verify(credentials).getRequestMetadata(eq(expectedUri));
  verify(applier).apply(headersCaptor.capture());
  Metadata headers = headersCaptor.getValue();
  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"token1"},
      Iterables.toArray(authorization, String.class));
}
 
源代码5 项目: bazel   文件: BlazeOptionHandlerTest.java
@Test
public void testStructureRcOptionsAndConfigs_importedRcs() throws Exception {
  ListMultimap<String, RcChunkOfArgs> structuredRc =
      BlazeOptionHandler.structureRcOptionsAndConfigs(
          eventHandler,
          Arrays.asList("rc1", "rc2"),
          Arrays.asList(
              new ClientOptions.OptionOverride(0, "c0", "a"),
              new ClientOptions.OptionOverride(0, "c0:config", "b"),
              new ClientOptions.OptionOverride(1, "common", "c"),
              new ClientOptions.OptionOverride(1, "c0", "d"),
              new ClientOptions.OptionOverride(1, "c0", "e"),
              new ClientOptions.OptionOverride(1, "c1:other", "f"),
              new ClientOptions.OptionOverride(1, "c1:other", "g"),
              new ClientOptions.OptionOverride(0, "c0", "h")),
          ImmutableSet.of("c0", "c1"));
  assertThat(structuredRc).isEqualTo(structuredArgsFromImportedRcsWithOnlyResidue());
  assertThat(eventHandler.isEmpty()).isTrue();
}
 
private static void formatDependencyPathTree(
    StringBuilder stringBuilder,
    ListMultimap<DependencyPath, DependencyPath> tree,
    DependencyPath currentNode,
    int depth) {
  Artifact leaf = currentNode.getLeaf();
  if (leaf != null) {
    // Nodes at top have one or more depth
    stringBuilder.append(Strings.repeat("  ", depth));
    stringBuilder.append(leaf);
    stringBuilder.append("\n");
    depth++;
  }
  for (DependencyPath childPath : tree.get(currentNode)) {
    if (!currentNode.equals(childPath)) { // root node's parent is the root itself
      formatDependencyPathTree(stringBuilder, tree, childPath, depth);
    }
  }
}
 
源代码7 项目: trainbenchmark   文件: TrainBenchmarkTest.java
@Test
public void posLengthInjectTest() throws Exception {
	// Arrange
	final String modelFilename = "railway-inject-" + largeSize;
	final String workload = "PosLengthInjectTest";
	final List<RailwayOperation> operations = ImmutableList.of(//
			RailwayOperation.POSLENGTH, //
			RailwayOperation.POSLENGTH_INJECT //
	);
	final BenchmarkConfigBase bcb = bcbbTransformation.setModelFilename(modelFilename).setOperations(operations)
			.setWorkload(workload).createConfigBase();

	// Act
	final BenchmarkResult result = runTest(bcb);

	// Assert
	final ListMultimap<RailwayQuery, Integer> allMatches = result.getLastRunResult().getMatches();
	collector.checkThat(allMatches.get(RailwayQuery.POSLENGTH).get(0), Matchers.equalTo(32));
	collector.checkThat(allMatches.get(RailwayQuery.POSLENGTH).get(1), Matchers.equalTo(41));
}
 
源代码8 项目: Pushjet-Android   文件: TaskDetailPrinter.java
private ListMultimap<Class, Task> groupTasksByType(List<Task> tasks) {
    final Set<Class> taskTypes = new TreeSet<Class>(new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    taskTypes.addAll(collect(tasks, new Transformer<Class, Task>() {
        public Class transform(Task original) {
            return getDeclaredTaskType(original);
        }
    }));

    ListMultimap<Class, Task> tasksGroupedByType = ArrayListMultimap.create();
    for (final Class taskType : taskTypes) {
        tasksGroupedByType.putAll(taskType, filter(tasks, new Spec<Task>() {
            public boolean isSatisfiedBy(Task element) {
                return getDeclaredTaskType(element).equals(taskType);
            }
        }));
    }
    return tasksGroupedByType;
}
 
public ListMultimap<PickingSlotId, PickedHUEditorRow> //
		retrieveAllPickedHUsIndexedByPickingSlotId(@NonNull final List<I_M_PickingSlot> pickingSlots)
{
	final SetMultimap<PickingSlotId, HuId> //
	huIdsByPickingSlotId = Services.get(IHUPickingSlotDAO.class).retrieveAllHUIdsIndexedByPickingSlotId(pickingSlots);

	final HUEditorViewRepository huEditorRepo = getHUEditorViewRepository();
	huEditorRepo.warmUp(ImmutableSet.copyOf(huIdsByPickingSlotId.values()));

	return huIdsByPickingSlotId
			.entries()
			.stream()
			.map(pickingSlotAndHU -> {
				final PickingSlotId pickingSlotId = pickingSlotAndHU.getKey();
				final HuId huId = pickingSlotAndHU.getValue();

				final HUEditorRow huEditorRow = huEditorRepo.retrieveForHUId(huId);
				final boolean pickingCandidateProcessed = true;
				final PickedHUEditorRow row = new PickedHUEditorRow(huEditorRow, pickingCandidateProcessed);

				return GuavaCollectors.entry(pickingSlotId, row);
			})
			.collect(GuavaCollectors.toImmutableListMultimap());
}
 
@Nullable
public ResourceValue getConfiguredValue(
        @NonNull ResourceType type,
        @NonNull String name,
        @NonNull FolderConfiguration referenceConfig) {
    // get the resource item for the given type
    ListMultimap<String, ResourceItem> items = getMap(type, false);
    if (items == null) {
        return null;
    }

    List<ResourceItem> keyItems = items.get(name);
    if (keyItems == null) {
        return null;
    }

    // look for the best match for the given configuration
    // the match has to be of type ResourceFile since that's what the input list contains
    ResourceItem match = (ResourceItem) referenceConfig.findMatchingConfigurable(keyItems);
    return match != null ? match.getResourceValue(mFramework) : null;
}
 
源代码11 项目: dagger2-sample   文件: ModuleValidator.java
@Override
public ValidationReport<TypeElement> validate(final TypeElement subject) {
  final ValidationReport.Builder<TypeElement> builder = ValidationReport.Builder.about(subject);

  List<ExecutableElement> moduleMethods = ElementFilter.methodsIn(subject.getEnclosedElements());
  ListMultimap<String, ExecutableElement> allMethodsByName = ArrayListMultimap.create();
  ListMultimap<String, ExecutableElement> bindingMethodsByName = ArrayListMultimap.create();
  for (ExecutableElement moduleMethod : moduleMethods) {
    if (isAnnotationPresent(moduleMethod, methodClass)) {
      bindingMethodsByName.put(moduleMethod.getSimpleName().toString(), moduleMethod);
    }
    allMethodsByName.put(moduleMethod.getSimpleName().toString(), moduleMethod);
  }
    
  validateModuleVisibility(subject, builder);
  validateMethodsWithSameName(builder, bindingMethodsByName);
  validateProvidesOverrides(subject, builder, allMethodsByName, bindingMethodsByName);
  validateModifiers(subject, builder);    
  validateReferencedModules(subject, builder);
  
  // TODO(gak): port the dagger 1 module validation?
  return builder.build();
}
 
源代码12 项目: dremio-oss   文件: AssignmentCreator.java
/**
 * Does the work of creating the mappings for this AssignmentCreator
 * @return the minor fragment id to work units mapping
 */
private ListMultimap<Integer, T> getMappings() {
  Stopwatch watch = Stopwatch.createStarted();
  maxWork = (int) Math.ceil(units.size() / ((float) incomingEndpoints.size()));
  LinkedList<WorkEndpointListPair<T>> workList = getWorkList();
  LinkedList<WorkEndpointListPair<T>> unassignedWorkList;
  Map<NodeEndpoint,FragIteratorWrapper> endpointIterators = getEndpointIterators();

  unassignedWorkList = assign(workList, endpointIterators, true);

  assignLeftovers(unassignedWorkList, endpointIterators, true);
  assignLeftovers(unassignedWorkList, endpointIterators, false);

  if (!unassignedWorkList.isEmpty()) {
    throw new IllegalStateException("There are still unassigned work units");
  }

  logger.debug("Took {} ms to assign {} work units to {} fragments", watch.elapsed(TimeUnit.MILLISECONDS), units.size(), incomingEndpoints.size());
  return mappings;
}
 
private List<PPOrderLineRow> createRowsForBomLines(
		@NonNull final I_PP_Order ppOrder,
		@NonNull final ListMultimap<Integer, I_PP_Order_Qty> ppOrderQtysByBOMLineId)
{
	final Comparator<PPOrderLineRow> ppOrderBomLineRowSorter = //
			Comparator.<PPOrderLineRow> comparingInt(row -> row.isReceipt() ? 0 : 1) // receipt lines first
					.thenComparing(row -> row.getOrderBOMLineId());  // BOM lines order

	final Function<? super I_PP_Order_BOMLine, ? extends PPOrderLineRow> ppOrderBomLineRowCreator = //
			ppOrderBOMLine -> createRowForBOMLine(
					ppOrderBOMLine,
					isReadOnly(ppOrder),
					ppOrderQtysByBOMLineId.get(ppOrderBOMLine.getPP_Order_BOMLine_ID()));

	final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
	final ImmutableList<PPOrderLineRow> bomLineRows = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class)
			.stream()
			.map(ppOrderBomLineRowCreator)
			.sorted(ppOrderBomLineRowSorter)
			.collect(ImmutableList.toImmutableList());
	return bomLineRows;
}
 
源代码14 项目: bazel   文件: ConfigExpander.java
/**
 * If --enable_platform_specific_config is true and the corresponding config definition exists, we
 * should enable the platform specific config.
 */
private static boolean shouldEnablePlatformSpecificConfig(
    OptionValueDescription enablePlatformSpecificConfigDescription,
    ListMultimap<String, RcChunkOfArgs> commandToRcArgs,
    List<String> commandsToParse) {
  if (enablePlatformSpecificConfigDescription == null
      || !(boolean) enablePlatformSpecificConfigDescription.getValue()) {
    return false;
  }

  for (String commandName : commandsToParse) {
    String defaultConfigDef = commandName + ":" + getPlatformName();
    if (commandToRcArgs.containsKey(defaultConfigDef)) {
      return true;
    }
  }
  return false;
}
 
源代码15 项目: java-n-IDE-for-Android   文件: DataMerger.java
/**
 * Sets the post blob load state to WRITTEN.
 *
 * After a load from the blob file, all items have their state set to nothing.
 * If the load mode is set to incrementalState then we want the items that are in the current
 * merge result to have their state be WRITTEN.
 *
 * This will allow further updates with {@link #mergeData(MergeConsumer, boolean)} to ignore the
 * state at load time and only apply the new changes.
 *
 * @see #loadFromBlob(File, boolean)
 * @see DataItem#isWritten()
 */
private void setPostBlobLoadStateToWritten() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // put all the sets into list per keys. The order is important as the lower sets are
    // overridden by the higher sets.
    for (S dataSet : mDataSets) {
        ListMultimap<String, I> map = dataSet.getDataMap();
        for (Map.Entry<String, Collection<I>> entry : map.asMap().entrySet()) {
            itemMap.putAll(entry.getKey(), entry.getValue());
        }
    }

    // the items that represent the current state is the last item in the list for each key.
    for (String key : itemMap.keySet()) {
        List<I> itemList = itemMap.get(key);
        itemList.get(itemList.size() - 1).resetStatusToWritten();
    }
}
 
源代码16 项目: Strata   文件: SensitivityCsvLoaderTest.java
@Test
public void test_parse_list() {
  CharSource source =
      ResourceLocator.ofClasspath("com/opengamma/strata/loader/csv/sensitivity-list.csv").getCharSource();

  assertThat(LOADER.isKnownFormat(source)).isTrue();
  ValueWithFailures<ListMultimap<String, CurveSensitivities>> test = LOADER.parse(ImmutableList.of(source));
  assertThat(test.getFailures().size()).as(test.getFailures().toString()).isEqualTo(0);
  assertThat(test.getValue().size()).isEqualTo(1);
  List<CurveSensitivities> list = test.getValue().get("");
  assertThat(list).hasSize(1);

  CurveSensitivities csens0 = list.get(0);
  assertThat(csens0.getTypedSensitivities()).hasSize(3);
  String tenors = "1D, 1W, 2W, 1M, 3M, 6M, 12M, 2Y, 5Y, 10Y";
  assertSens(csens0, ZERO_RATE_DELTA, "GBP", GBP, tenors, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  assertSens(csens0, ZERO_RATE_DELTA, "GBP-LIBOR", GBP, tenors, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  assertSens(csens0, ZERO_RATE_GAMMA, "GBP", GBP, tenors, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1);
  assertSens(csens0, ZERO_RATE_GAMMA, "GBP-LIBOR", GBP, tenors, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1);
  assertSens(csens0, OTHER, "GBP", GBP, tenors, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0);
  assertSens(csens0, OTHER, "GBP-LIBOR", GBP, tenors, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0);

  assertThat(LOADER.parseAndMerge(ImmutableList.of(source)).getValue()).isEqualTo(csens0);
}
 
源代码17 项目: Strata   文件: SwapTradeCsvPlugin.java
private static SwapTrade parseVariableNotional(SwapTrade trade, List<CsvRow> variableRows) {
  ImmutableList<SwapLeg> legs = trade.getProduct().getLegs();
  ListMultimap<Integer, ValueStep> steps =
      extractSteps(variableRows, legs, NOTIONAL_FIELD, str -> LoaderUtils.parseDouble(str));
  if (steps.isEmpty()) {
    return trade;
  }
  // adjust the trade, inserting the variable element
  ImmutableList.Builder<SwapLeg> legBuilder = ImmutableList.builder();
  for (int i = 0; i < legs.size(); i++) {
    SwapLeg swapLeg = legs.get(i);
    List<ValueStep> legSteps = steps.get(i);
    if (!legSteps.isEmpty() && swapLeg instanceof RateCalculationSwapLeg) {
      RateCalculationSwapLeg leg = (RateCalculationSwapLeg) swapLeg;
      NotionalSchedule notionalSchedule = leg.getNotionalSchedule().toBuilder()
          .amount(ValueSchedule.of(leg.getNotionalSchedule().getAmount().getInitialValue(), legSteps))
          .build();
      swapLeg = leg.toBuilder().notionalSchedule(notionalSchedule).build();
    }
    legBuilder.add(swapLeg);
  }
  return replaceLegs(trade, legBuilder.build());
}
 
源代码18 项目: hmftools   文件: DiploidRatioSupplier.java
DiploidRatioSupplier(@NotNull final ListMultimap<Chromosome, ReadRatio> normalRatios) {
    final ReferenceRatioStatistics stats = ReferenceRatioStatisticsFactory.fromReferenceRatio(normalRatios);

    for (Chromosome chromosome : normalRatios.keySet()) {
        final List<ReadRatio> ratios = normalRatios.get(chromosome);
        final List<ReadRatio> adjustedRatios;
        if (chromosome.equals(HumanChromosome._Y)) {
            adjustedRatios = ratios;
        } else {
            double expectedRatio = chromosome.equals(HumanChromosome._X) && !stats.containsTwoXChromosomes() ? 0.5 : 1;
            adjustedRatios = new DiploidRatioNormalization(expectedRatio,
                    ROLLING_MEDIAN_MAX_DISTANCE,
                    ROLLING_MEDIAN_MIN_COVERAGE,
                    ratios).get();
        }
        result.replaceValues(chromosome, adjustedRatios);
    }
}
 
源代码19 项目: sfs   文件: PostContainer.java
public PostContainer(HttpClient httpClient, String accountName, String containerName, Producer auth, ListMultimap<String, String> headers) {
    this.httpClient = httpClient;
    this.accountName = accountName;
    this.containerName = containerName;
    this.auth = auth;
    this.headers = headers;
}
 
源代码20 项目: grpc-nebula-java   文件: NettyServerStreamTest.java
@Test
public void closeAfterClientHalfCloseShouldSucceed() throws Exception {
  ListMultimap<CharSequence, CharSequence> expectedHeaders =
      ImmutableListMultimap.copyOf(new DefaultHttp2Headers()
          .status(new AsciiString("200"))
          .set(new AsciiString("content-type"), new AsciiString("application/grpc"))
          .set(new AsciiString("grpc-status"), new AsciiString("0")));

  // Client half-closes. Listener gets halfClosed()
  stream().transportState()
      .inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true);

  verify(serverListener).halfClosed();

  // Server closes. Status sent
  stream().close(Status.OK, trailers);
  assertNull("no message expected", listenerMessageQueue.poll());

  ArgumentCaptor<SendResponseHeadersCommand> cmdCap =
      ArgumentCaptor.forClass(SendResponseHeadersCommand.class);
  verify(writeQueue).enqueue(cmdCap.capture(), eq(true));
  SendResponseHeadersCommand cmd = cmdCap.getValue();
  assertThat(cmd.stream()).isSameAs(stream.transportState());
  assertThat(ImmutableListMultimap.copyOf(cmd.headers()))
      .containsExactlyEntriesIn(expectedHeaders);
  assertThat(cmd.endOfStream()).isTrue();

  // Sending and receiving complete. Listener gets closed()
  stream().transportState().complete();
  verify(serverListener).closed(Status.OK);
  assertNull("no message expected", listenerMessageQueue.poll());
}
 
源代码21 项目: rack-servlet   文件: TestHttpServletRequest.java
private TestHttpServletRequest(String method, String servletPath, URI uri,
    ListMultimap<String, String> headers, String body, Map<String, Object>
    attributes) {
  this.method = method;
  this.servletPath = servletPath;
  this.uri = uri;
  this.headers = headers;
  this.body = body;
  this.attributes = attributes;
}
 
源代码22 项目: swift-t   文件: ForeachLoops.java
private ForeachLoop(Block block,
    String loopName, Var container, Var loopVar,
    Var loopCounterVar, int splitDegree, int leafDegree,
    boolean arrayClosed,
    List<PassedVar> passedVars, List<Var> keepOpenVars,
    List<RefCount> startIncrements,
    ListMultimap<Var, RefCount> constStartIncrements,
    List<RefCount> endDecrements, boolean emptyBody) {
  super(block, loopName, loopVar, loopCounterVar, splitDegree, leafDegree,
      -1, false, passedVars, keepOpenVars, startIncrements, constStartIncrements,
      endDecrements, emptyBody);
  this.container = container;
  this.containerClosed = arrayClosed;
}
 
@Test
@SuppressWarnings("unchecked")
public void credentialsReturnNullMetadata() throws Exception {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  when(credentials.getRequestMetadata(eq(expectedUri)))
      .thenReturn(null, Multimaps.<String, String>asMap(values), null);

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  for (int i = 0; i < 3; i++) {
    callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
  }

  verify(credentials, times(3)).getRequestMetadata(eq(expectedUri));

  verify(applier, times(3)).apply(headersCaptor.capture());
  List<Metadata> headerList = headersCaptor.getAllValues();
  assertEquals(3, headerList.size());

  assertEquals(0, headerList.get(0).keys().size());

  Iterable<String> authorization = headerList.get(1).getAll(AUTHORIZATION);
  assertArrayEquals(new String[]{"token1"}, Iterables.toArray(authorization, String.class));

  assertEquals(0, headerList.get(2).keys().size());
}
 
源代码24 项目: swift-t   文件: ComponentGraph.java
/**
 * Add edge, avoiding duplicates
 * @param parents2
 * @param child
 * @param edge
 */
private void addEdge(ListMultimap<Node, Edge> edgeLists, Node src, Edge edge) {
  // NOTE: this potentially requires linear search, but in practice lists should
  // generally be quite short
  List<Edge> edges = edgeLists.get(src);
  if (!edges.contains(edge)) {
    edgeLists.put(src, edge);
  }
}
 
源代码25 项目: tablesaw   文件: TableSliceGroup.java
/**
 * Applies the given aggregations to the given columns. The apply and combine steps of a
 * split-apply-combine.
 *
 * @param functions map from column name to aggregation to apply on that function
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public Table aggregate(ListMultimap<String, AggregateFunction<?, ?>> functions) {
  Table groupTable = summaryTableName(sourceTable);
  StringColumn groupColumn = StringColumn.create("Group");
  groupTable.addColumns(groupColumn);
  boolean firstFunction = true;
  for (Map.Entry<String, Collection<AggregateFunction<?, ?>>> entry :
      functions.asMap().entrySet()) {
    String columnName = entry.getKey();
    for (AggregateFunction function : entry.getValue()) {
      String colName = aggregateColumnName(columnName, function.functionName());
      ColumnType type = function.returnType();
      Column resultColumn = type.create(colName);
      for (TableSlice subTable : getSlices()) {
        Object result = function.summarize(subTable.column(columnName));
        if (firstFunction) {
          groupColumn.append(subTable.name());
        }
        if (result instanceof Number) {
          Number number = (Number) result;
          resultColumn.append(number.doubleValue());
        } else {
          resultColumn.append(result);
        }
      }
      groupTable.addColumns(resultColumn);
      firstFunction = false;
    }
  }
  return splitGroupingColumn(groupTable);
}
 
源代码26 项目: bazel-buildfarm   文件: RedisShardSubscriberTest.java
@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();
}
 
源代码27 项目: hmftools   文件: ClusterFactory.java
@NotNull
private ListMultimap<Chromosome, Cluster> cluster(@NotNull final Multimap<Chromosome, SVSegment> variantPositions,
        @NotNull final Multimap<Chromosome, PCFPosition> pcfPositions, @NotNull final ListMultimap<Chromosome, CobaltRatio> ratios) {
    ListMultimap<Chromosome, Cluster> clusters = ArrayListMultimap.create();
    for (Chromosome chromosome : pcfPositions.keySet()) {
        final Collection<PCFPosition> chromosomePcfPositions = pcfPositions.get(chromosome);
        final List<CobaltRatio> chromosomeRatios = ratios.containsKey(chromosome) ? ratios.get(chromosome) : Lists.newArrayList();
        final Collection<SVSegment> chromosomeVariants =
                variantPositions.containsKey(chromosome) ? variantPositions.get(chromosome) : Lists.newArrayList();
        clusters.putAll(chromosome, cluster(chromosomeVariants, chromosomePcfPositions, chromosomeRatios));
    }

    return clusters;
}
 
static
private <K, C extends ParameterCell> ListMultimap<K, C> groupCells(List<C> cells, Function<C, K> function){
	ListMultimap<K, C> result = ArrayListMultimap.create();

	for(C cell : cells){
		result.put(function.apply(cell), cell);
	}

	return result;
}
 
public static String roleForPort(final long port, @NotNull final ListMultimap<String, Resource> index) {
    Optional<Resource> offeredPorts = from(index.get("ports"))
            .filter(containsPort(port))
            .first();

    if (offeredPorts.isPresent()) {
        return offeredPorts.get().getRole();
    } else {
        return "*";
    }
}
 
private PickingSlotRow createPickingSlotRow(
		@NonNull final I_M_PickingSlot pickingSlot,
		@NonNull final ListMultimap<PickingSlotId, PickedHUEditorRow> huEditorRowsByPickingSlotId)
{
	final List<PickingSlotRow> pickedHuRows = retrieveHuRowsToIncludeInPickingSlotRow(pickingSlot, huEditorRowsByPickingSlotId);
	return createPickingSlotRowWithIncludedRows(pickingSlot, pickedHuRows);
}
 
 同包方法