Java 类com.google.common.collect.Multimaps 实例源码

项目:GitHub    文件:LongBits.java   
LongPositions(Iterable<? extends Object> elements, final int bitPerLong) {
  this.elements = ImmutableList.copyOf(elements);
  checkArgument(bitPerLong <= BITS_IN_LONG, bitPerLong);

  for (int i = 0; i < this.elements.size(); i++) {
    positions.put(
        this.elements.get(i),
        new BitPosition(
            i / bitPerLong,
            i % bitPerLong));
  }

  this.longPositions = ImmutableSortedMap.copyOf(
      Maps.transformEntries(
          Multimaps.index(positions.values(), ToLongIndex.FUNCTION).asMap(),
          new Maps.EntryTransformer<Integer, Collection<BitPosition>, LongSet>() {
            @Override
            public LongSet transformEntry(Integer key, Collection<BitPosition> position) {
              return new LongSet(key, position);
            }
          }));
}
项目:HardVox    文件:TaskManager.java   
public void runTasks() {
    Multimaps.asMap(ImmutableListMultimap.copyOf(taskQueue)).values().forEach(tasks -> {
        int size = tasks.size();
        while (size > 0) {
            int last = size - 1;
            Task<?> current = tasks.get(last);
            if (current.done()) {
                taskQueue.get(current.getClass()).remove(last);
                size--;
                continue;
            }
            current.tick();
            return;
        }
    });
}
项目:powsybl-core    文件:ImpactAnalysisTool.java   
private static Multimap<String, SecurityIndex> runImpactAnalysis(Network network, Set<String> contingencyIds,
                                                                 ComputationManager computationManager, SimulatorFactory simulatorFactory,
                                                                 ContingenciesProvider contingenciesProvider,
                                                                 PrintStream out) throws Exception {
    Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0);
    ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingenciesProvider);
    Map<String, Object> initContext = new HashMap<>();
    SimulationParameters simulationParameters = SimulationParameters.load();
    stabilization.init(simulationParameters, initContext);
    impactAnalysis.init(simulationParameters, initContext);
    out.println("running stabilization simulation...");
    StabilizationResult sr = stabilization.run();
    out.println("stabilization status: " + sr.getStatus());
    out.println("stabilization metrics: " + sr.getMetrics());
    if (sr.getStatus() == StabilizationStatus.COMPLETED) {
        out.println("running impact analysis...");
        ImpactAnalysisResult iar = impactAnalysis.run(sr.getState(), contingencyIds);
        out.println("impact analysis metrics: " + iar.getMetrics());

        return Multimaps.index(iar.getSecurityIndexes(), securityIndex -> securityIndex.getId().getContingencyId());

    }
    return null;
}
项目:tac-kbp-eal    文件:_CorpusQueryAssessments.java   
public final CorpusQueryAssessments filterForAssessment(final Set<QueryAssessment2016> assessment2016) {
  final ImmutableSet.Builder<QueryResponse2016> matchingQueriesB = ImmutableSet.builder();
  for (final QueryResponse2016 queryResponse2016 : assessments().keySet()) {
    if (assessment2016.contains(assessments().get(queryResponse2016))) {
      matchingQueriesB.add(queryResponse2016);
    }
  }
  final ImmutableSet<QueryResponse2016> matchingQueries = matchingQueriesB.build();
  final CorpusQueryAssessments.Builder ret = CorpusQueryAssessments.builder();
  ret.queryReponses(matchingQueries);
  ret.putAllQueryResponsesToSystemIDs(
      Multimaps.filterKeys(queryResponsesToSystemIDs(), in(matchingQueries)));
  ret.putAllMetadata(Maps.filterKeys(metadata(), in(matchingQueries)));
  ret.putAllAssessments(Maps.filterKeys(assessments(), in(matchingQueries)));
  return ret.build();
}
项目:tac-kbp-eal    文件:SameEventTypeLinker.java   
private ResponseLinking linkResponses(final Symbol docId,
    final Iterable<Response> responses) {
  final Predicate<Response> HasRelevantRealis =
      compose(in(realisesWhichMustBeAligned), ResponseFunctions.realis());
  final ImmutableSet<Response> systemResponsesAlignedRealis =
      FluentIterable.from(responses).filter(HasRelevantRealis).toSet();

  final Multimap<Symbol, Response> responsesByEventType =
      Multimaps.index(systemResponsesAlignedRealis, ResponseFunctions.type());

  final ImmutableSet.Builder<ResponseSet> ret = ImmutableSet.builder();

  for (final Collection<Response> responseSet : responsesByEventType.asMap().values()) {
    ret.add(ResponseSet.from(responseSet));
  }

  return ResponseLinking.builder().docID(docId).addAllResponseSets(ret.build()).build();
}
项目:drift    文件:AbstractThriftMetadataBuilder.java   
/**
 * Assigns all fields an id if possible.  Fields are grouped by name and for each group, if there
 * is a single id, all fields in the group are assigned this id.  If the group has multiple ids,
 * an error is reported.
 */
protected final Set<String> inferThriftFieldIds()
{
    Set<String> fieldsWithConflictingIds = new HashSet<>();

    // group fields by explicit name or by name extracted from field, method or property
    Multimap<String, FieldMetadata> fieldsByExplicitOrExtractedName = Multimaps.index(fields, FieldMetadata::getOrExtractThriftFieldName);
    inferThriftFieldIds(fieldsByExplicitOrExtractedName, fieldsWithConflictingIds);

    // group fields by name extracted from field, method or property
    // this allows thrift name to be set explicitly without having to duplicate the name on getters and setters
    // todo should this be the only way this works?
    Multimap<String, FieldMetadata> fieldsByExtractedName = Multimaps.index(fields, FieldMetadata::extractName);
    inferThriftFieldIds(fieldsByExtractedName, fieldsWithConflictingIds);

    return fieldsWithConflictingIds;
}
项目:guava-mock    文件:MediaType.java   
private String computeToString() {
  StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
  if (!parameters.isEmpty()) {
    builder.append("; ");
    Multimap<String, String> quotedParameters =
        Multimaps.transformValues(
            parameters,
            new Function<String, String>() {
              @Override
              public String apply(String value) {
                return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
              }
            });
    PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
  }
  return builder.toString();
}
项目:Equella    文件:AbstractIntegrationService.java   
private SetMultimap<String, IntegrationSessionExtension> getExtensionMap()
{
    if( extensionMap == null )
    {
        synchronized( this )
        {
            if( extensionMap == null )
            {
                final SetMultimap<String, IntegrationSessionExtension> map = HashMultimap
                    .<String, IntegrationSessionExtension>create();
                for( Extension ext : resultsTracker.getExtensions() )
                {
                    final IntegrationSessionExtension integExtension = resultsTracker.getBeanByExtension(ext);
                    for( Parameter parameter : ext.getParameters("type") )
                    {
                        map.put(parameter.valueAsString(), integExtension);
                    }
                }
                extensionMap = Multimaps.unmodifiableSetMultimap(map);
            }
        }
    }
    return extensionMap;
}
项目:athena    文件:DefaultRouter.java   
@Activate
public void activate() {
    ribTable4 = new ConcurrentInvertedRadixTree<>(
            new DefaultByteArrayNodeFactory());
    ribTable6 = new ConcurrentInvertedRadixTree<>(
            new DefaultByteArrayNodeFactory());

    routesWaitingOnArp = Multimaps.synchronizedSetMultimap(
            HashMultimap.create());

    coreService.registerApplication(ROUTER_APP_ID);

    bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder()
            .setNameFormat("rib-updates-%d").build());
}
项目:googles-monorepo-demo    文件:MediaType.java   
private String computeToString() {
  StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
  if (!parameters.isEmpty()) {
    builder.append("; ");
    Multimap<String, String> quotedParameters =
        Multimaps.transformValues(
            parameters,
            new Function<String, String>() {
              @Override
              public String apply(String value) {
                return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
              }
            });
    PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
  }
  return builder.toString();
}
项目:apollo-custom    文件:RemoteConfigLongPollService.java   
/**
 * Constructor.
 */
public RemoteConfigLongPollService() {
  m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
  m_longPollingStopped = new AtomicBoolean(false);
  m_longPollingService = Executors.newSingleThreadExecutor(
      ApolloThreadFactory.create("RemoteConfigLongPollService", true));
  m_longPollStarted = new AtomicBoolean(false);
  m_longPollNamespaces =
      Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
  m_notifications = Maps.newConcurrentMap();
  m_remoteNotificationMessages = Maps.newConcurrentMap();
  m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
  }.getType();
  gson = new Gson();
  m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
  m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
  m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
项目:hashsdn-controller    文件:DOMNotificationRouter.java   
@Override
public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
    final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
        @Override
        protected void removeRegistration() {
            final ListenerRegistration<T> me = this;

            synchronized (DOMNotificationRouter.this) {
                replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, input -> input != me)));
            }
        }
    };

    if (!types.isEmpty()) {
        final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
        b.putAll(listeners);

        for (final SchemaPath t : types) {
            b.put(t, reg);
        }

        replaceListeners(b.build());
    }

    return reg;
}
项目:Mastering-Mesos    文件:Maintenance.java   
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getHosts() {
  return storage.read(storeProvider -> {
    Multimap<MaintenanceMode, String> hostsByMode =
        Multimaps.transformValues(
          Multimaps.index(
              storeProvider.getAttributeStore().getHostAttributes(),
              IHostAttributes::getMode),
            IHostAttributes::getHost);

    Map<MaintenanceMode, Object> hosts = ImmutableMap.of(
        DRAINED, ImmutableSet.copyOf(hostsByMode.get(DRAINED)),
        SCHEDULED, ImmutableSet.copyOf(hostsByMode.get(SCHEDULED)),
        DRAINING, getTasksByHosts(storeProvider, hostsByMode.get(DRAINING)).asMap());
    return Response.ok(hosts).build();
  });
}
项目:Mastering-Mesos    文件:SchedulerThriftInterface.java   
private static Set<InstanceTaskConfig> buildInitialState(Map<Integer, ITaskConfig> tasks) {
  // Translate tasks into instance IDs.
  Multimap<ITaskConfig, Integer> instancesByConfig = HashMultimap.create();
  Multimaps.invertFrom(Multimaps.forMap(tasks), instancesByConfig);

  // Reduce instance IDs into contiguous ranges.
  Map<ITaskConfig, Set<Range<Integer>>> rangesByConfig =
      Maps.transformValues(instancesByConfig.asMap(), Numbers::toRanges);

  ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder();
  for (Map.Entry<ITaskConfig, Set<Range<Integer>>> entry : rangesByConfig.entrySet()) {
    builder.add(new InstanceTaskConfig()
        .setTask(entry.getKey().newBuilder())
        .setInstances(IRange.toBuildersSet(convertRanges(entry.getValue()))));
  }

  return builder.build();
}
项目:Mastering-Mesos    文件:ReadOnlySchedulerImpl.java   
@Override
public Response getRoleSummary() {
  Multimap<String, IJobKey> jobsByRole = storage.read(
      storeProvider ->
          Multimaps.index(storeProvider.getTaskStore().getJobKeys(), IJobKey::getRole));

  Multimap<String, IJobKey> cronJobsByRole = Multimaps.index(
      Iterables.transform(Storage.Util.fetchCronJobs(storage), IJobConfiguration::getKey),
      IJobKey::getRole);

  Set<RoleSummary> summaries = FluentIterable.from(
      Sets.union(jobsByRole.keySet(), cronJobsByRole.keySet()))
      .transform(role -> new RoleSummary(
          role,
          jobsByRole.get(role).size(),
          cronJobsByRole.get(role).size()))
      .toSet();

  return ok(Result.roleSummaryResult(new RoleSummaryResult(summaries)));
}
项目:apollo    文件:RemoteConfigLongPollService.java   
/**
 * Constructor.
 */
public RemoteConfigLongPollService() {
  m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
  m_longPollingStopped = new AtomicBoolean(false);
  m_longPollingService = Executors.newSingleThreadExecutor(
      ApolloThreadFactory.create("RemoteConfigLongPollService", true));
  m_longPollStarted = new AtomicBoolean(false);
  m_longPollNamespaces =
      Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
  m_notifications = Maps.newConcurrentMap();
  m_remoteNotificationMessages = Maps.newConcurrentMap();
  m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
  }.getType();
  gson = new Gson();
  m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
  m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
  m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
项目:hmftools    文件:LoadStructuralVariants.java   
@NotNull
private static List<EnrichedStructuralVariant> enrichStructuralVariants(@NotNull List<StructuralVariant> variants,
        @NotNull DatabaseAccess dbAccess, @NotNull String tumorSample) {
    final PurityContext purityContext = dbAccess.readPurityContext(tumorSample);

    if (purityContext == null) {
        LOGGER.warn("Unable to retrieve purple data. Enrichment may be incomplete.");
    }

    final PurityAdjuster purityAdjuster = purityContext == null
            ? new PurityAdjuster(Gender.FEMALE, 1, 1)
            : new PurityAdjuster(purityContext.gender(), purityContext.bestFit().purity(), purityContext.bestFit().normFactor());

    final List<PurpleCopyNumber> copyNumberList = dbAccess.readCopynumbers(tumorSample);
    final Multimap<String, PurpleCopyNumber> copyNumbers = Multimaps.index(copyNumberList, PurpleCopyNumber::chromosome);
    return EnrichedStructuralVariantFactory.enrich(variants, purityAdjuster, copyNumbers);
}
项目:endpoints-java    文件:JsonConfigWriter.java   
@Override
public Map<ApiKey, String> writeConfig(Iterable<? extends ApiConfig> configs)
    throws ApiConfigException {
  Multimap<ApiKey, ? extends ApiConfig> apisByKey = Multimaps.index(configs,
      new Function<ApiConfig, ApiKey>() {
        @Override public ApiKey apply(ApiConfig config) {
          return config.getApiKey();
        }
      });

  // This *must* retain the order of apisByKey so the lily_java_api BUILD rule has predictable
  // output order.
  Map<ApiKey, String> results = Maps.newLinkedHashMap();
  for (ApiKey apiKey : apisByKey.keySet()) {
    Collection<? extends ApiConfig> apiConfigs = apisByKey.get(apiKey);
    validator.validate(apiConfigs);
    results.put(apiKey, generateForApi(apiConfigs));
  }
  return results;
}
项目:emodb    文件:AstyanaxBlockedDataReaderDAO.java   
/**
 * Gets the topology for a Cassandra keyspace as a Multimap, where the keys identify a rack (or availability zone
 * in Amazon) and the values are the token ranges for each host in that rack.  For example, for a well distributed
 * ring of 12 hosts and a replication factor of 3 this method would return a Multimap with 3 keys and each key would
 * contain 4 token ranges.
 */
private Multimap<String, TokenRange> describeCassandraTopology(final Keyspace keyspace) {
    try {
        @SuppressWarnings ("unchecked")
        ConnectionPool<Cassandra.Client> connectionPool = (ConnectionPool<Cassandra.Client>) keyspace.getConnectionPool();

        return connectionPool.executeWithFailover(
                new AbstractKeyspaceOperationImpl<Multimap<String, TokenRange>>(EmptyKeyspaceTracerFactory.getInstance().newTracer(CassandraOperationType.DESCRIBE_RING), keyspace.getKeyspaceName()) {
                    @Override
                    protected Multimap<String, TokenRange> internalExecute(Cassandra.Client client, ConnectionContext state)
                            throws Exception {
                        Multimap<String, TokenRange> racks = ArrayListMultimap.create();
                        for (org.apache.cassandra.thrift.TokenRange tokenRange : client.describe_local_ring(getKeyspace())) {
                            // The final local endpoint "owns" the token range, the rest are for replication
                            EndpointDetails endpointDetails = Iterables.getLast(tokenRange.getEndpoint_details());
                            racks.put(endpointDetails.getRack(),
                                    new TokenRangeImpl(tokenRange.getStart_token(), tokenRange.getEnd_token(), tokenRange.getEndpoints()));
                        }
                        return Multimaps.unmodifiableMultimap(racks);
                    }
                },
                keyspace.getConfig().getRetryPolicy().duplicate()).getResult();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
}
项目:emodb    文件:AstyanaxDataReaderDAO.java   
/**
 * Gets the topology for a Cassandra keyspace as a Multimap, where the keys identify a rack (or availability zone
 * in Amazon) and the values are the token ranges for each host in that rack.  For example, for a well distributed
 * ring of 12 hosts and a replication factor of 3 this method would return a Multimap with 3 keys and each key would
 * contain 4 token ranges.
 */
private Multimap<String, TokenRange> describeCassandraTopology(final Keyspace keyspace) {
    try {
        @SuppressWarnings ("unchecked")
        ConnectionPool<Cassandra.Client> connectionPool = (ConnectionPool<Cassandra.Client>) keyspace.getConnectionPool();

        return connectionPool.executeWithFailover(
                new AbstractKeyspaceOperationImpl<Multimap<String, TokenRange>>(EmptyKeyspaceTracerFactory.getInstance().newTracer(CassandraOperationType.DESCRIBE_RING), keyspace.getKeyspaceName()) {
                    @Override
                    protected Multimap<String, TokenRange> internalExecute(Cassandra.Client client, ConnectionContext state)
                            throws Exception {
                        Multimap<String, TokenRange> racks = ArrayListMultimap.create();
                        for (org.apache.cassandra.thrift.TokenRange tokenRange : client.describe_local_ring(getKeyspace())) {
                            // The final local endpoint "owns" the token range, the rest are for replication
                            EndpointDetails endpointDetails = Iterables.getLast(tokenRange.getEndpoint_details());
                            racks.put(endpointDetails.getRack(),
                                    new TokenRangeImpl(tokenRange.getStart_token(), tokenRange.getEnd_token(), tokenRange.getEndpoints()));
                        }
                        return Multimaps.unmodifiableMultimap(racks);
                    }
                },
                keyspace.getConfig().getRetryPolicy().duplicate()).getResult();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
}
项目:codebuff    文件:MediaType.java   
private String computeToString() {
  StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
  if (!parameters.isEmpty()) {
    builder.append("; ");
    Multimap<String, String> quotedParameters =
        Multimaps.transformValues(
            parameters,
            new Function<String, String>() {
              @Override
              public String apply(String value) {
                return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
              }
            });
    PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
  }
  return builder.toString();
}
项目:beam    文件:ApiSurface.java   
/** See {@link #getExposedToExposers}. */
private void constructExposedToExposers() {
  visited = Sets.newHashSet();
  exposedToExposers =
      Multimaps.newSetMultimap(
          Maps.<Class<?>, Collection<Class<?>>>newHashMap(),
          new Supplier<Set<Class<?>>>() {
            @Override
            public Set<Class<?>> get() {
              return Sets.newHashSet();
            }
          });

  for (Class<?> clazz : rootClasses) {
    addExposedTypes(clazz, null);
  }
}
项目:xtext-core    文件:Validator.java   
protected Multimap<URI, MWEDiagnostic> groupByURI(MWEDiagnostic[] diagnostic) {
    Multimap<URI, MWEDiagnostic> result = Multimaps.newMultimap(
            Maps.<URI, Collection<MWEDiagnostic>> newLinkedHashMap(), new Supplier<Collection<MWEDiagnostic>>() {
                @Override
                public Collection<MWEDiagnostic> get() {
                    return Sets.newTreeSet(getDiagnosticComparator());
                }
            });
    result.putAll(Multimaps.index(Arrays.asList(diagnostic), new Function<MWEDiagnostic, URI>() {
        @Override
        public URI apply(MWEDiagnostic from) {
            Issue issue = (Issue) from.getElement();
            URI uriToProblem = issue.getUriToProblem();
            return uriToProblem != null ? uriToProblem.trimFragment() : NullURI;
        }
    }));
    return result;
}
项目:dsl-devkit    文件:CheckJavaValidator.java   
/**
 * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
 * to a string which is used for checking for duplicates.
 *
 * @param <T>
 *          the generic type
 * @param predicate
 *          the predicate acting as a guard
 * @param function
 *          returns a string for an instance of type T
 * @param elements
 *          the elements to be checked
 * @return the duplicates
 */
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
  List<T> result = Lists.newArrayList();
  Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
    @Override
    public Collection<T> get() {
      return Lists.<T> newArrayList();
    }
  });
  for (final T candidate : elements) {
    if (predicate.apply(candidate)) {
      multiMap.put(function.apply(candidate), candidate);
    }
  }
  for (String elem : multiMap.keySet()) {
    final Collection<T> duplicates = multiMap.get(elem);
    if (duplicates.size() > 1) {
      result.addAll(duplicates);
    }
  }

  return result;
}
项目:dsl-devkit    文件:CheckCfgJavaValidator.java   
/**
 * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
 * to a string which is used for checking for duplicates.
 *
 * @param <T>
 *          the generic type
 * @param predicate
 *          the predicate acting as a guard
 * @param function
 *          returns a string for an instance of type T
 * @param elements
 *          the elements to be checked
 * @return the duplicates
 */
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
  List<T> result = Lists.newArrayList();
  Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
    @Override
    public Collection<T> get() {
      return Lists.<T> newArrayList();
    }
  });
  for (final T candidate : elements) {
    if (predicate.apply(candidate)) {
      multiMap.put(function.apply(candidate), candidate);
    }
  }
  for (String elem : multiMap.keySet()) {
    final Collection<T> duplicates = multiMap.get(elem);
    if (duplicates.size() > 1) {
      result.addAll(duplicates);
    }
  }

  return result;
}
项目:jira-dvcs-connector    文件:ChangesetServiceImpl.java   
@Override
public List<Changeset> getChangesetsWithFileDetails(List<Changeset> changesets)
{
    ImmutableList.Builder<Changeset> detailedChangesets = ImmutableList.builder();

    // group by repo so we only have to load each repo one time inside the loop
    ListMultimap<Integer, Changeset> changesetsByRepo = Multimaps.index(changesets, Changesets.TO_REPOSITORY_ID);
    for (Map.Entry<Integer, Collection<Changeset>> repoChangesets : changesetsByRepo.asMap().entrySet())
    {
        final Repository repository = repositoryDao.get(repoChangesets.getKey());
        final DvcsCommunicator communicator = dvcsCommunicatorProvider.getCommunicator(repository.getDvcsType());
        processRepository(repository, repoChangesets.getValue(), communicator, detailedChangesets);
    }

    return detailedChangesets.build();
}
项目:FreeBuilder    文件:ListMultimapProperty.java   
private void addGetter(SourceBuilder code, Metadata metadata) {
  code.addLine("")
      .addLine("/**")
      .addLine(" * Returns an unmodifiable view of the multimap that will be returned by")
      .addLine(" * %s.", metadata.getType().javadocNoArgMethodLink(property.getGetterName()))
      .addLine(" * Changes to this builder will be reflected in the view.")
      .addLine(" */")
      .addLine("public %s<%s, %s> %s() {",
          ListMultimap.class,
          keyType,
          valueType,
          getter(property))
      .addLine("  return %s.unmodifiableListMultimap(%s);",
          Multimaps.class, property.getField())
      .addLine("}");
}
项目:FreeBuilder    文件:SetMultimapProperty.java   
private void addGetter(SourceBuilder code, Metadata metadata) {
  code.addLine("")
      .addLine("/**")
      .addLine(" * Returns an unmodifiable view of the multimap that will be returned by")
      .addLine(" * %s.", metadata.getType().javadocNoArgMethodLink(property.getGetterName()))
      .addLine(" * Changes to this builder will be reflected in the view.")
      .addLine(" */")
      .addLine("public %s<%s, %s> %s() {",
          SetMultimap.class,
          keyType,
          valueType,
          getter(property))
      .addLine("  return %s.unmodifiableSetMultimap(%s);",
          Multimaps.class, property.getField())
      .addLine("}");
}
项目:FreeBuilder    文件:ListMultimapMutateMethodTest.java   
@Test
public void mutateAndAddAtIndexViaAsMapModifiesUnderlyingProperty() {
  behaviorTester
      .with(new Processor(features))
      .with(CHECKED_PROPERTY)
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putAllItems(\"one\", ImmutableList.of(\"A\", \"B\", \"C\"))")
          .addLine("    .mutateItems(items -> %s.asMap(items).get(\"one\").add(2, \"foo\"))",
              Multimaps.class)
          .addLine("    .build();")
          .addLine("assertThat(value.getItems())")
          .addLine("    .contains(\"one\", \"A\", \"B\", \"foo\", \"C\")")
          .addLine("    .andNothingElse()")
          .addLine("    .inOrder();")
          .build())
      .runTest();
}
项目:FreeBuilder    文件:ListMultimapMutateMethodTest.java   
@Test
public void mutateAndAddAtIndexViaAsMapKeepsSubstitute() {
  behaviorTester
      .with(new Processor(features))
      .with(INTERNED_PROPERTY)
      .with(testBuilder()
          .addLine("String s = new String(\"foobar\");")
          .addLine("String i = s.intern();")
          .addLine("assertThat(s).isNotSameAs(i);")
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putAllItems(\"one\", ImmutableList.of(\"A\", \"B\", \"C\"))")
          .addLine("    .mutateItems(items -> %s.asMap(items).get(\"one\").add(2, s))",
              Multimaps.class)
          .addLine("    .build();")
          .addLine("assertThat(value.getItems().get(\"one\").get(2)).isSameAs(i);")
          .build())
      .runTest();
}
项目:consultant    文件:Consultant.java   
private Consultant(ScheduledExecutorService executor, ObjectMapper mapper, URI consulUri,
        ServiceIdentifier identifier, SetMultimap<String, SettingListener> settingListeners,
        Set<ConfigListener> configListeners, ConfigValidator validator, CloseableHttpClient http,
        boolean pullConfig, String healthEndpoint, String kvPrefix) {

    this.registered = new AtomicBoolean();
    this.settingListeners = Multimaps.synchronizedSetMultimap(settingListeners);
    this.configListeners = Sets.newConcurrentHashSet(configListeners);
    this.serviceInstanceBackend = new ServiceInstanceBackend(identifier.getDatacenter(), consulUri, mapper, http);
    this.mapper = mapper;
    this.validator = validator;
    this.executor = executor;
    this.consulUri = consulUri;
    this.id = identifier;
    this.pullConfig = pullConfig;
    this.validated = new Properties();
    this.healthEndpoint = healthEndpoint;
    this.http = http;
       this.kvPrefix = kvPrefix;
}
项目:onetwo    文件:GuavaTest.java   
@Test
public void testGroupBy(){
    List<UserEntity> all = LangUtils.newArrayList();
    List<UserEntity> aa = createUserList("aa", 3);
    List<UserEntity> bb = createUserList("bb", 1);
    List<UserEntity> cc = createUserList("cc", 2);
    all.addAll(aa);
    all.addAll(bb);
    all.addAll(cc);

    ImmutableListMultimap<String, UserEntity> groups = Multimaps.index(all, new Function<UserEntity, String>() {

        @Override
        public String apply(UserEntity input) {
            return input.getUserName();
        }

    });

    System.out.println("groups:" + groups);
    Assert.assertEquals(3, groups.get("aa").size());
    Assert.assertEquals(1, groups.get("bb").size());
    Assert.assertEquals(2, groups.get("cc").size());
}
项目:jklol    文件:IntMultimap.java   
/**
 * Creates a new multimap that reverses the keys and values in {@code map}.
 * 
 * @param map
 * @return
 */
public static IntMultimap invertFrom(Multimap<? extends Integer, ? extends Integer> map) {
  if (map instanceof IntMultimap) {
    IntMultimap other = (IntMultimap) map;
    // This is unnecessary, but it makes this method easier to implement.
    other.reindexItems();

    int[] newSortedKeys = Arrays.copyOf(other.sortedValues, other.sortedValues.length);
    int[] newSortedValues = Arrays.copyOf(other.sortedKeys, other.sortedKeys.length);

    ArrayUtils.sortKeyValuePairs(newSortedKeys, newSortedValues, 0, newSortedKeys.length);

    return new IntMultimap(newSortedKeys, newSortedValues);
  } else {
    IntMultimap inverse = IntMultimap.create();
    Multimaps.invertFrom(map, inverse);
    return inverse;
  }
}
项目:presto    文件:FunctionRegistry.java   
public FunctionMap(FunctionMap map, Iterable<? extends SqlFunction> functions)
{
    this.functions = ImmutableListMultimap.<QualifiedName, SqlFunction>builder()
            .putAll(map.functions)
            .putAll(Multimaps.index(functions, function -> QualifiedName.of(function.getSignature().getName())))
            .build();

    // Make sure all functions with the same name are aggregations or none of them are
    for (Map.Entry<QualifiedName, Collection<SqlFunction>> entry : this.functions.asMap().entrySet()) {
        Collection<SqlFunction> values = entry.getValue();
        long aggregations = values.stream()
                .map(function -> function.getSignature().getKind())
                .filter(kind -> kind == AGGREGATE || kind == APPROXIMATE_AGGREGATE)
                .count();
        checkState(aggregations == 0 || aggregations == values.size(), "'%s' is both an aggregation and a scalar function", entry.getKey());
    }
}
项目:presto    文件:PartitionUpdate.java   
public static List<PartitionUpdate> mergePartitionUpdates(List<PartitionUpdate> unMergedUpdates)
{
    ImmutableList.Builder<PartitionUpdate> partitionUpdates = ImmutableList.builder();
    for (Collection<PartitionUpdate> partitionGroup : Multimaps.index(unMergedUpdates, PartitionUpdate::getName).asMap().values()) {
        PartitionUpdate firstPartition = partitionGroup.iterator().next();

        ImmutableList.Builder<String> allFileNames = ImmutableList.builder();
        for (PartitionUpdate partition : partitionGroup) {
            // verify partitions have the same new flag, write path and target path
            // this shouldn't happen but could if another user added a partition during the write
            if (partition.isNew() != firstPartition.isNew() ||
                    !partition.getWritePath().equals(firstPartition.getWritePath()) ||
                    !partition.getTargetPath().equals(firstPartition.getTargetPath())) {
                throw new PrestoException(HIVE_WRITER_ERROR, format("Partition %s was added or modified during INSERT", firstPartition.getName()));
            }
            allFileNames.addAll(partition.getFileNames());
        }

        partitionUpdates.add(new PartitionUpdate(firstPartition.getName(),
                firstPartition.isNew(),
                firstPartition.getWritePath(),
                firstPartition.getTargetPath(),
                allFileNames.build()));
    }
    return partitionUpdates.build();
}
项目:onboard    文件:WebsocketHandler.java   
public void sendMessage(String userEmail, String message) {

        Multimap<String, WebSocketSession> syncMap = Multimaps.synchronizedMultimap(userPagesMap);
        Collection<WebSocketSession> mis = syncMap.get(userEmail);
        synchronized (syncMap) {
            if (mis != null) {
                Iterator<WebSocketSession> it = mis.iterator();
                while (it.hasNext()) {
                    WebSocketSession session = it.next();
                    try {
                        session.sendMessage(new TextMessage(message));
                    } catch (Exception e) {
                        logger.info("The WebSocket connection has been closed: " + session.toString());
                    }

                }
            }
        }

    }
项目:onboard    文件:WebSocketServiceImpl.java   
@Override
public void broadcastOne(String user, String message) {
    Multimap<String, MessageInbound> syncMap = Multimaps.synchronizedMultimap(userPagesMap);
    Collection<MessageInbound> mis = syncMap.get(user);
    synchronized (syncMap) {
        if (mis != null) {
            Iterator<MessageInbound> it = mis.iterator();
            while (it.hasNext()) {
                MessageInbound inbound = it.next();
                try {
                    sendToPage(inbound, message);
                } catch (IOException e) {
                    // userPagesMap.remove(user, inbound);
                    logger.info("The WebSocket connection has been closed: " + inbound.toString());
                }

            }
        }
    }
}
项目:gradle-workspace-plugin    文件:WorkspacePlugin.java   
/**
 * Get the configurations that export an artifact
 *
 * @param projects Projects to search
 * @return Exporting configurations
 */
protected Multimap<@NonNull String, @NonNull ExportingConfiguration> getExportingConfigurations(
        Collection<@NonNull Project> projects) {
    Multimap<@NonNull String, @NonNull ExportingConfiguration> exports = Multimaps.newSetMultimap(new HashMap<>(),
            () -> new TreeSet<>(CONFIGURATION_INFO_COMPARATOR));

    for (Project project : projects) {
        Set<String> configurationNames = ImmutableSet.of("default");
        WorkspaceConfig workspaceConfig = project.getExtensions().findByType(WorkspaceConfig.class);

        if (workspaceConfig != null) {
            configurationNames = workspaceConfig.getExportedConfigurations();
        }

        for (String configurationName : configurationNames) {
            Configuration configuration = project.getConfigurations().findByName(configurationName);

            if (configuration != null) {
                getExportingConfigurations(project, configuration, exports);
            }
        }
    }

    return exports;
}
项目:artifactory    文件:WatchesServiceImpl.java   
private void lazyInitCacheIfNeeded() {
    if (!initialized) {
        synchronized (this) {
            if (!initialized) {
                if (watchersCache == null) {
                    watchersCache = HashMultimap.create();
                    watchersCache = Multimaps.synchronizedMultimap(watchersCache);
                }

                try {
                    //TODO: [by YS] consider using single query to get watch + repo path
                    List<Watch> nodeWatches = watchesDao.getWatches();
                    for (Watch nodeWatch : nodeWatches) {
                        RepoPath repoPath = fileService.loadItem(nodeWatch.getNodeId()).getRepoPath();
                        watchersCache.put(repoPath, nodeWatch);
                    }
                    initialized = true;
                } catch (SQLException e) {
                    throw new StorageException("Failed to load watches", e);
                }
            }
        }
    }
}
项目:metadict    文件:BilingualEntryMerger.java   
@NotNull
@Override
protected Collection<Collection<BilingualEntry>> findCandidates(@NotNull Collection<BilingualEntry> normalizedInput) {
    Multimap<MergeCandidateIdentifier, BilingualEntry> candidatesMap = buildMergeCandidateMultimap(normalizedInput);
    Multimap<MergeCandidateIdentifier, BilingualEntry> knownMap = Multimaps.filterEntries(candidatesMap, this::toNullIfUnknown);
    Multimap<MergeCandidateIdentifier, BilingualEntry> unknownMap = Multimaps.filterEntries(candidatesMap, this::toNullIfKnown);
    Collection<Collection<BilingualEntry>> candidates = new ArrayList<>(candidatesMap.keys().size());

    identifyUnknownEntryTypeCandidates(candidatesMap, knownMap, unknownMap, candidates);
    mergeSingleDialectLanguages(candidatesMap);

    for (MergeCandidateIdentifier key : knownMap.asMap().keySet()) {
        candidates.add(candidatesMap.get(key));
    }

    return candidates;
}