Java Code Examples for com.google.common.collect.ListMultimap#put()
The following examples show how to use
com.google.common.collect.ListMultimap#put() .
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: ClientAuthInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 7 votes |
@Test public void testCopyCredentialToHeaders() throws IOException { ListMultimap<String, String> values = LinkedListMultimap.create(); values.put("Authorization", "token1"); values.put("Authorization", "token2"); values.put("Extra-Authorization", "token3"); values.put("Extra-Authorization", "token4"); when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values)); ClientCall<String, Integer> interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel); Metadata headers = new Metadata(); interceptedCall.start(listener, headers); assertEquals(listener, call.responseListener); assertEquals(headers, call.headers); Iterable<String> authorization = headers.getAll(AUTHORIZATION); Assert.assertArrayEquals(new String[]{"token1", "token2"}, Iterables.toArray(authorization, String.class)); Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION); Assert.assertArrayEquals(new String[]{"token3", "token4"}, Iterables.toArray(extraAuthorization, String.class)); }
Example 2
Source File: AbstractSchemaRepository.java From yangtools with Eclipse Public License 1.0 | 6 votes |
private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source, final AbstractSchemaSourceRegistration<T> reg) { ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> map = sources.get(source.getSourceIdentifier()); if (map == null) { map = ArrayListMultimap.create(); sources.put(source.getSourceIdentifier(), map); } map.put(source.getRepresentation(), reg); final Collection<PotentialSchemaSource<?>> reps = Collections.singleton(source); for (SchemaListenerRegistration l : listeners) { l.getInstance().schemaSourceRegistered(reps); } }
Example 3
Source File: CascadedDynamicConfigurationSource.java From caravan with Apache License 2.0 | 6 votes |
private ListMultimap<String, PropertyChangeEvent> getRealPropertyChangeEventsMultiMap(ConfigurationSourceChangeEvent event) { ListMultimap<String, PropertyChangeEvent> propertyChangeEventsMultiMap = ArrayListMultimap.create(); for (PropertyChangeEvent propertyChangeEvent : event.propertyChangeEvents()) { String key = propertyChangeEvent.key(); String realKey = null; for (String cascadedKeyPart : cascadedConfiguration().cascadedKeyParts()) { if (realKey == null) { String cascadedKey = StringValues.trimEnd(key, cascadedKeyPart); if (!cascadedKey.equals(key)) realKey = cascadedKey; } if (realKey != null) propertyChangeEventsMultiMap.put(realKey + cascadedKeyPart, propertyChangeEvent); } if (realKey == null) propertyChangeEventsMultiMap.put(key, propertyChangeEvent); } return propertyChangeEventsMultiMap; }
Example 4
Source File: GroupRepository.java From artemis with Apache License 2.0 | 6 votes |
protected Map<Long, GroupTags> getServiceGroupTags() { Map<Long, GroupTags> newGroupTags = Maps.newHashMap(); ListMultimap<Long, GroupTagModel> m = ArrayListMultimap.create(); for (GroupTagModel model : groupTagDao.query()) { m.put(model.getGroupId(), model); } for (Long id : m.keySet()) { Map<String, String> tags = Maps.newHashMap(); for (GroupTagModel tag : m.get(id)) { tags.put(tag.getTag(), tag.getValue()); } newGroupTags.put(id, new GroupTags(id, tags)); } return newGroupTags; }
Example 5
Source File: AmberVCF.java From hmftools with GNU General Public License v3.0 | 6 votes |
public void writeBAF(@NotNull final String filename, @NotNull final Collection<TumorBAF> tumorEvidence, @NotNull final AmberHetNormalEvidence hetNormalEvidence) { final List<TumorBAF> list = Lists.newArrayList(tumorEvidence); Collections.sort(list); final VariantContextWriter writer = new VariantContextWriterBuilder().setOutputFile(filename).modifyOption(Options.INDEX_ON_THE_FLY, true).build(); final VCFHeader header = header(config.tumorOnly() ? Collections.singletonList(config.tumor()) : config.allSamples()); writer.setHeader(header); writer.writeHeader(header); final ListMultimap<AmberSite, Genotype> genotypeMap = ArrayListMultimap.create(); for (final String sample : hetNormalEvidence.samples()) { for (BaseDepth baseDepth : hetNormalEvidence.evidence(sample)) { genotypeMap.put(AmberSiteFactory.asSite(baseDepth), createGenotype(sample, baseDepth)); } } for (final TumorBAF tumorBAF : list) { AmberSite tumorSite = AmberSiteFactory.tumorSite(tumorBAF); genotypeMap.put(tumorSite, createGenotype(tumorBAF)); writer.add(create(tumorBAF, genotypeMap.get(tumorSite))); } writer.close(); }
Example 6
Source File: HttpAsyncRequestExecutors.java From caravan with Apache License 2.0 | 6 votes |
public static <T> ListenableFuture<T> execute(Executor executor, CloseableHttpAsyncClient client, String uri, String method, ListMultimap<String, String> headers, RequestConfig config, Object data, StreamSerializer serializer, Class<T> clazz) { config = RequestConfigs.createCascadedRequestConfig(client, config); if (serializer != null) { if (headers == null) headers = ArrayListMultimap.create(); if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) headers.put(HttpHeaders.CONTENT_TYPE, serializer.contentType()); if (!headers.containsKey(HttpHeaders.ACCEPT)) headers.put(HttpHeaders.ACCEPT, serializer.contentType()); } HttpUriRequest request = HttpRequestFactory.createRequest(uri, method, headers, config, data, serializer, false); return execute(executor, client, request, serializer, clazz); }
Example 7
Source File: CobaltRatioFile.java From hmftools with GNU General Public License v3.0 | 5 votes |
@NotNull private static ListMultimap<Chromosome, CobaltRatio> fromLines(@NotNull final List<String> lines) { final ListMultimap<Chromosome, CobaltRatio> result = ArrayListMultimap.create(); for (int i = 1; i < lines.size(); i++) { String line = lines.get(i); final CobaltRatio ratio = fromLine(line); result.put(HumanChromosome.fromString(ratio.chromosome()), ratio); } return result; }
Example 8
Source File: AstyanaxEventWriterDAO.java From emodb with Apache License 2.0 | 5 votes |
@Override public void delete(String channel, Collection<EventId> eventIds) { checkNotNull(channel, "channel"); checkNotNull(eventIds, "eventIds"); ListMultimap<ByteBuffer, Integer> eventsBySlab = ArrayListMultimap.create(); for (EventId eventId : eventIds) { AstyanaxEventId eventIdImpl = (AstyanaxEventId) eventId; checkArgument(channel.equals(eventIdImpl.getChannel())); eventsBySlab.put(eventIdImpl.getSlabId(), eventIdImpl.getEventIdx()); } // We might be able to use weak consistency since we're allowed to forget deletes and repeat events. But we'd // need to measure it in production to see how frequently weak consistency would cause events to repeat. BatchUpdate update = new BatchUpdate(_keyspace, ConsistencyLevel.CL_LOCAL_QUORUM, Constants.MUTATION_MAX_ROWS, Constants.MUTATION_MAX_COLUMNS); for (Map.Entry<ByteBuffer, Collection<Integer>> entry : eventsBySlab.asMap().entrySet()) { ByteBuffer slabId = entry.getKey(); Collection<Integer> eventIdxs = entry.getValue(); BatchUpdate.Row<ByteBuffer, Integer> row = update.updateRow(ColumnFamilies.SLAB, slabId); for (Integer eventIdx : eventIdxs) { row.deleteColumn(eventIdx); } } update.finish(); }
Example 9
Source File: GeneralRegressionModelEvaluator.java From jpmml-evaluator with GNU Affero General Public License v3.0 | 5 votes |
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; }
Example 10
Source File: ReorderInstructions.java From swift-t with Apache License 2.0 | 5 votes |
private void addDependencies(Logger logger, Function fn, ArrayList<StatementInfo> stmtInfos, int i, boolean forwardEdges, ListMultimap<Integer, Integer> before) { StatementInfo info1 = stmtInfos.get(i); if (logger.isTraceEnabled()) logger.trace("addDependencies " + info1); // Find last instruction that writes inputs of inst1 // Build a DAG of dependences between instructions for (int j = i + 1; j < stmtInfos.size(); j++) { StatementInfo info2 = stmtInfos.get(j); // TODO: should check for "expensive" statements to avoid // deferring execution by putting instruction after it if (forwardEdges && writesInputs(logger, info2, info1, false)) { // These edges wont create cycle - backward edge before.put(j, i); } if (!forwardEdges && writesInputs(logger, info1, info2, true)) { // Check that there isn't a path from inst1 to inst2 if (pathExists(before, j, i)) { if (logger.isTraceEnabled()) { logger.trace("Drop edge " + j + " => " + i + " to avoid cycle"); } } else { before.put(i, j); } } } }
Example 11
Source File: AbstractResourceRepository.java From java-n-IDE-for-Android with Apache License 2.0 | 5 votes |
private void addItem(@NonNull ResourceItem item) { synchronized (ITEM_MAP_LOCK) { ListMultimap<String, ResourceItem> map = getMap(item.getType()); if (!map.containsValue(item)) { map.put(item.getName(), item); } } }
Example 12
Source File: TrieTest.java From ambiverse-nlu with Apache License 2.0 | 5 votes |
@Test public void testTrieChinese() throws Exception { Set<String> dictionary = new TreeSet<>(); dictionary.add("马拉多纳"); dictionary.add("1986年世界杯"); FST<Long> trie = TrieBuilder.buildTrie(dictionary); String text = "马拉多纳扮演1986年世界杯。"; Set<Integer> begginingPositions = new HashSet<>(); Set<Integer> endingPrositions = new HashSet<>(); Tokens tokens = UimaTokenizer.tokenize(Language.getLanguageForString("zh"), text); for(Token token: tokens.getTokens()) { begginingPositions.add(token.getBeginIndex()); endingPrositions.add(token.getEndIndex()); } Set<Spot> spots = TextSpotter.spotTrieEntriesInTextIgnoreCase(trie,text,begginingPositions,endingPrositions,0.9); assertEquals(spots.size(), 2); ListMultimap<String, Spot> results = ArrayListMultimap.create(); for(Spot spot : spots) { String concept = Utils.getStringbyKey(spot.getMatch(), trie); results.put(concept, spot); String textMatch = text.substring(spot.getBegin(), spot.getEnd()); // System.out.println("CONCEPT: " + concept + " TEXT MATCH: " + textMatch + " begin: " + spot.getBegin() + " end: " + spot.getEnd()); } assertTrue(results.containsKey("马拉多纳")); Spot maradona = results.get("马拉多纳").get(0); assertEquals(maradona.getBegin(), 0); assertEquals(maradona.getEnd(), 4); assertTrue(results.containsKey("1986年世界杯")); Spot worldCup = results.get("1986年世界杯").get(0); assertEquals(worldCup.getBegin(), 6); assertEquals(worldCup.getEnd(), 14); }
Example 13
Source File: ExtractJsonPathsBuilder.java From kite with Apache License 2.0 | 5 votes |
public ExtractJsonPaths(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) { super(builder, config, parent, child, context); ListMultimap<String, String> stepMultiMap = ArrayListMultimap.create(); this.flatten = getConfigs().getBoolean(config, "flatten", true); Config paths = getConfigs().getConfig(config, "paths"); for (Map.Entry<String, Object> entry : new Configs().getEntrySet(paths)) { String fieldName = entry.getKey(); String path = entry.getValue().toString().trim(); if (path.contains("//")) { throw new MorphlineCompilationException("No support for descendant axis available yet", config); } if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } path = path.trim(); for (String step : path.split("/")) { step = step.trim(); if (step.length() > ARRAY_TOKEN.length() && step.endsWith(ARRAY_TOKEN)) { step = step.substring(0, step.length() - ARRAY_TOKEN.length()); stepMultiMap.put(fieldName, normalize(step)); stepMultiMap.put(fieldName, ARRAY_TOKEN); } else { stepMultiMap.put(fieldName, normalize(step)); } } } this.stepMap = stepMultiMap.asMap(); LOG.debug("stepMap: {}", stepMap); validateArguments(); }
Example 14
Source File: ModelManagerFactory.java From jpmml-evaluator with GNU Affero General Public License v3.0 | 5 votes |
static private <S extends ModelManager<?>> ListMultimap<Class<? extends Model>, Class<? extends S>> loadServiceProviderClasses(Class<S> serviceClazz) throws ClassNotFoundException, IOException { Thread thread = Thread.currentThread(); ClassLoader clazzLoader = thread.getContextClassLoader(); if(clazzLoader == null){ clazzLoader = ClassLoader.getSystemClassLoader(); } ListMultimap<Class<? extends Model>, Class<? extends S>> result = ArrayListMultimap.create(); Enumeration<URL> urls = clazzLoader.getResources("META-INF/services/" + serviceClazz.getName()); while(urls.hasMoreElements()){ URL url = urls.nextElement(); try(InputStream is = url.openStream()){ List<? extends Class<? extends S>> serviceProviderClazzes = loadServiceProviderClasses(is, clazzLoader, serviceClazz); for(Class<? extends S> serviceProviderClazz : serviceProviderClazzes){ Class<? extends Model> modelClazz = findModelParameter(serviceClazz, serviceProviderClazz); result.put(modelClazz, serviceProviderClazz); } } } return result; }
Example 15
Source File: Entropy.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
public static ListMultimap<FeatureVectorAsObject, Integer> getHPosContextCategoryMap(Corpus corpus) { ListMultimap<FeatureVectorAsObject, Integer> hposByFeatureVectorGroup = ArrayListMultimap.create(); int numContexts = corpus.featureVectors.size(); for (int i = 0; i<numContexts; i++) { int[] X = corpus.featureVectors.get(i); int y = corpus.hpos.get(i); hposByFeatureVectorGroup.put(new FeatureVectorAsObject(X, Trainer.FEATURES_HPOS), y); } return hposByFeatureVectorGroup; }
Example 16
Source File: BlazeOptionHandlerTest.java From bazel with Apache License 2.0 | 5 votes |
private static ListMultimap<String, RcChunkOfArgs> structuredArgsForDifferentPlatforms() { ListMultimap<String, RcChunkOfArgs> structuredArgs = ArrayListMultimap.create(); structuredArgs.put("c0:linux", new RcChunkOfArgs("rc1", ImmutableList.of("command_linux"))); structuredArgs.put("c0:windows", new RcChunkOfArgs("rc1", ImmutableList.of("command_windows"))); structuredArgs.put("c0:macos", new RcChunkOfArgs("rc1", ImmutableList.of("command_macos"))); structuredArgs.put("c0:freebsd", new RcChunkOfArgs("rc1", ImmutableList.of("command_freebsd"))); structuredArgs.put("c0:openbsd", new RcChunkOfArgs("rc1", ImmutableList.of("command_openbsd"))); structuredArgs.put( "c0:platform_config", new RcChunkOfArgs("rc1", ImmutableList.of("--enable_platform_specific_config"))); return structuredArgs; }
Example 17
Source File: ImmutableSortedKeyListMultimapTest.java From bazel with Apache License 2.0 | 5 votes |
@Test public void copyOfWithDuplicates() { ListMultimap<String, Integer> input = ArrayListMultimap.create(); input.put("foo", 1); input.put("bar", 2); input.put("foo", 3); input.put("foo", 1); Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.copyOf(input); assertThat(input).isEqualTo(multimap); assertThat(multimap).isEqualTo(input); }
Example 18
Source File: TableJson.java From emodb with Apache License 2.0 | 4 votes |
TableJson(Map<String, Object> json) { super(json); // Get the uuid of the master primary storage. String masterUuid = get(UUID_ATTR); // Create 'Storage' objects that wrap all the json maps describing where data for this table lives. List<Storage> storages = Lists.newArrayList(); Map<String, Map<String, Object>> storageMap = get(STORAGE); if (storageMap != null) { for (Map.Entry<String, Map<String, Object>> entry : storageMap.entrySet()) { storages.add(new Storage(entry.getKey(), entry.getValue(), entry.getKey().equals(masterUuid))); } } _storages = storages; // Loop through the storage objects and organize the data into master, facades, expired, pick primaries. // This is the essence of the storage life cycle state machine w/an eventually consistent data store: // writers write the state markers they know, readers read them and sort out what actually happened. Storage master = null; List<Storage> facades = Lists.newArrayList(); // Bucket the active storage entries into groups, one group for the master and one for each facade. ListMultimap<String, Storage> groupMap = ArrayListMultimap.create(); for (Storage storage : storages) { if (!storage.hasTransitioned(StorageState.DROPPED)) { groupMap.put(storage.getGroupId(), storage); } } // Pick the primary storage in each group. The rest are mirrors. Set<String> facadePlacements = Sets.newHashSet(); for (Collection<Storage> group : groupMap.asMap().values()) { Storage primary = Storage.initializeGroup(group); if (primary == null) { continue; } if (!primary.isFacade()) { // Master data if (!primary.getUuidString().equals(masterUuid)) { // Looks like there are multiple primaries for the master. We always pick the one that matches // masterUuid, but we should log an error because this isn't supposed to happen. It is possible, // however, when quorum is broken--multiple Cassandra servers are lost and restored and data is // not repaired correctly. _log.error("Table {} has an orphaned master storage (uuid={}), please verify data integrity.", getTable(), primary.getUuidString()); continue; } master = primary; } else { // Facade data if (!facadePlacements.add(primary.getPlacement())) { // Multiple facades for the same placement is not supposed to happen, log an error. _log.error("Table {} has multiple facades for the same placement {} (uuid={}), please verify data integrity.", getTable(), primary.getPlacement(), primary.getUuidString()); continue; } facades.add(primary); } } _master = master; _facades = facades; }
Example 19
Source File: HardAssignmentCreator.java From dremio-oss with Apache License 2.0 | 4 votes |
public <T extends CompleteWork> ListMultimap<Integer, T> getMappings( final List<NodeEndpoint> endpoints, final List<T> units) throws PhysicalOperatorSetupException { verify(endpoints, units, units.size() >= endpoints.size(), "There should be at least one work unit for each hard affinity node."); // First, group endpoints by hostname. There could be multiple endpoints on same host final ListMultimap<String, Integer> endpointsOnHostMap = ArrayListMultimap.create(); int index = 0; for(NodeEndpoint incoming : endpoints) { endpointsOnHostMap.put(incoming.getAddress(), index); index++; } // Convert the multi-map <String,Integer> into a map <String, Iterator<Integer>> final Map<String, Iterator<Integer>> endpointIteratorOnHostMap = Maps.newHashMap(); for(Map.Entry<String, Collection<Integer>> entry: endpointsOnHostMap.asMap().entrySet()) { endpointIteratorOnHostMap.put(entry.getKey(), Iterables.cycle(entry.getValue()).iterator()); } final ListMultimap<Integer, T> mappings = ArrayListMultimap.create(); for(T unit: units) { final List<EndpointAffinity> affinities = unit.getAffinity(); verify(endpoints, units, affinities.size() == 1, "Expected the hard affinity work unit to have affinity to only one endpoint"); final EndpointAffinity endpointAffinity = affinities.get(0); final String host = endpointAffinity.getEndpoint().getAddress(); final Iterator<Integer> endpointsOnHost = endpointIteratorOnHostMap.get(host); if (endpointsOnHost == null) { verify(endpoints, units, false, "There are no endpoints in assigned list running on host %s", host); } final int endpointId = endpointIteratorOnHostMap.get(host).next(); mappings.put(endpointId, unit); } // Go through the mappings and make sure at least one unit for every assigned endpoint, // otherwise we will end up with fragments that don't have any work assigned. If an assignment is not present for // endpoint, throw an exception for(int i = 0; i < endpoints.size(); i++) { if (!mappings.containsKey(i)) { verify(endpoints, units, false, "Endpoint %s has no assigned work.", endpoints.get(i)); } } return mappings; }
Example 20
Source File: ActionListCustomizationMediatorImpl.java From rice with Educational Community License v2.0 | 4 votes |
/** * <p>partitions ActionItems by application id, and calls the appropriate * {@link ActionListCustomizationHandlerService} for each parition, merging the results.</p> * * <dl><dt><b>inherited docs:</b></dt><dd>{@inheritDoc}</dd></dl> */ @Override public Map<String, ActionItemCustomization> getActionListCustomizations(String principalId, List<ActionItem> actionItems) throws RiceIllegalArgumentException { if (StringUtils.isBlank(principalId)) { throw new RiceIllegalArgumentException("invalid principalId: " + principalId); } if (actionItems == null) { actionItems = Collections.emptyList(); } // map from action item ID to ActionItemCustomization Map<String, ActionItemCustomization> results = new HashMap<String, ActionItemCustomization>(); // group each action item by application id that needs to be called for action list customizations (note that // the application id comes from the extension/rule attribute record, most action lists will have doc types // with no custom action list attribute, though the default still needs to be run in this case) ListMultimap<String, ActionItem> itemsByApplicationId = ArrayListMultimap.create(); for (ActionItem actionItem : actionItems) { //DocumentType docType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(actionItem.getDocName()); DocumentType docType = getDocumentTypeService().findByName(actionItem.getDocName()); if (docType == null) { LOG.error(String.format("Action item %s has an invalid document type name of %s", actionItem.getId(), actionItem.getDocName())); // OK to have a null key, this represents the default app id itemsByApplicationId.put(null, actionItem); } else { // OK to have a null key, this represents the default app id itemsByApplicationId.put(getActionListCustomizationApplicationId(docType), actionItem); } } // For each application id, pass all action items which might need to be customized (because they have a // document type, which declares an action list attribute, which has an application id declared) to the // appropriate ActionListCustomizationHandlerService endpoint for (String applicationId : itemsByApplicationId.keySet()) { ActionListCustomizationHandlerService actionListCustomizationHandler = getActionListCustomizationHandlerServiceChooser().getByApplicationId(applicationId); if (actionListCustomizationHandler == null) { // get the local ActionListCustomizationHandlerService as a fallback actionListCustomizationHandler = getActionListCustomizationHandlerServiceChooser().getByApplicationId(null); } List<ActionItemCustomization> customizations = actionListCustomizationHandler.customizeActionList(principalId, itemsByApplicationId.get( applicationId)); // Get back the customized results and reassemble with customized results from all different application // customizations (as well as default customizations) if (customizations != null) for (ActionItemCustomization customization : customizations) { results.put(customization.getActionItemId(), customization); } } return results; }