Java Code Examples for com.google.common.collect.SetMultimap#put()

The following examples show how to use com.google.common.collect.SetMultimap#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: WorkerQueuesTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void gpuConfig_unvalidProvisionNotEnqueued() {

  // Arrange
  WorkerQueues queues = WorkerQueueConfigurations.gpu();

  // Act
  Operation operation = Operation.newBuilder().build();
  SetMultimap<String, String> provisions = HashMultimap.create();
  provisions.put("invalid_key", "invalid_value");
  boolean success = queues.enqueueOperation(operation, provisions);

  // Assert
  assertThat(success).isFalse();
  assertThat(queues.queueSize("GPU")).isEqualTo(0);
}
 
Example 2
Source File: BuilderParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.12
 */
protected Map<OutputConfiguration, Iterable<IMarker>> buildGeneratorMarkersReverseLookupMap(Map<OutputConfiguration, Iterable<IMarker>> generatorMarkers) {
	SetMultimap<String, IFile> reverseLookupMap = HashMultimap.create();
	for (java.util.Map.Entry<OutputConfiguration, Iterable<IMarker>> entry : generatorMarkers.entrySet()) {
		OutputConfiguration outputConfiguration = entry.getKey();
		if (outputConfiguration.isCleanUpDerivedResources()) {
			for (IMarker marker : entry.getValue()) {
				String source = derivedResourceMarkers.getSource(marker);
				if (source != null) {
					reverseLookupMap.put(source, (IFile) marker.getResource());
				}
			}
		}
	}
	return new DerivedResourcesLookupMap(generatorMarkers, reverseLookupMap);
}
 
Example 3
Source File: Environment.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private static void getLocalAndInheritedColumnFields(PackageElement pkg,
                                                     TypeElement type,
                                                     SetMultimap<String, VariableElement> fields) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    getLocalAndInheritedColumnFields(pkg, asTypeElement(superInterface), fields);
  }
  if (type.getSuperclass().getKind() != TypeKind.NONE) {
    // Visit the superclass after superinterfaces so we will always see the implementation of a
    // method after any interfaces that declared it.
    getLocalAndInheritedColumnFields(pkg, asTypeElement(type.getSuperclass()), fields);
  }
  for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) {
    final Set<Modifier> modifiers = field.getModifiers();
    if (!modifiers.contains(Modifier.STATIC)) {
      fields.put(field.getSimpleName().toString(), field);
    }
  }
}
 
Example 4
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * @param entities field init info
 * @param state visitor state
 * @return a map from each constructor C to the nonnull fields that C does *not* initialize
 */
private SetMultimap<MethodTree, Symbol> checkConstructorInitialization(
    FieldInitEntities entities, VisitorState state) {
  SetMultimap<MethodTree, Symbol> result = LinkedHashMultimap.create();
  Set<Symbol> nonnullInstanceFields = entities.nonnullInstanceFields();
  Trees trees = getTreesInstance(state);
  boolean isExternalInit = isExternalInit(entities.classSymbol());
  for (MethodTree constructor : entities.constructors()) {
    if (constructorInvokesAnother(constructor, state)) {
      continue;
    }
    if (constructor.getParameters().size() == 0 && isExternalInit) {
      // external framework initializes fields in this case
      continue;
    }
    Set<Element> guaranteedNonNull =
        guaranteedNonNullForConstructor(entities, state, trees, constructor);
    for (Symbol fieldSymbol : nonnullInstanceFields) {
      if (!guaranteedNonNull.contains(fieldSymbol)) {
        result.put(constructor, fieldSymbol);
      }
    }
  }
  return result;
}
 
Example 5
Source File: DataBundleLogic.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private void processQuestionsAndPopulateMap(Collection<FeedbackQuestionAttributes> questions,
        SetMultimap<String, FeedbackQuestionAttributes> sessionQuestionsMap) {
    for (FeedbackQuestionAttributes question : questions) {
        question.removeIrrelevantVisibilityOptions();

        String sessionKey = makeSessionKey(question.feedbackSessionName, question.courseId);
        sessionQuestionsMap.put(sessionKey, question);
    }
}
 
Example 6
Source File: GeometricShapePart.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected SetMultimap<? extends Object, String> doGetContentAnchorages() {
	SetMultimap<Object, String> anchorages = HashMultimap.create();
	for (AbstractGeometricElement<? extends IGeometry> anchorage : getContent().getAnchorages()) {
		anchorages.put(anchorage, "link");
	}
	return anchorages;
}
 
Example 7
Source File: MethodFinder.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all methods, declared and inherited, on {@code type}, except those specified by
 * {@link Object}.
 *
 * <p>If method B overrides method A, only method B will be included in the return set.
 * Additionally, if methods A and B have the same signature, but are on unrelated interfaces,
 * one will be arbitrarily picked to be returned.
 */
public static <E extends Exception> ImmutableSet<ExecutableElement> methodsOn(
    TypeElement type,
    Elements elements,
    ErrorTypeHandling<E> errorTypeHandling) throws E {
  TypeElement objectType = elements.getTypeElement(Object.class.getCanonicalName());
  Map<Signature, ExecutableElement> objectMethods = Maps.uniqueIndex(
      methodsIn(objectType.getEnclosedElements()), Signature::new);
  SetMultimap<Signature, ExecutableElement> methods = LinkedHashMultimap.create();
  for (TypeElement supertype : getSupertypes(type, errorTypeHandling)) {
    for (ExecutableElement method : methodsIn(supertype.getEnclosedElements())) {
      Signature signature = new Signature(method);
      if (method.getEnclosingElement().equals(objectType)) {
        continue;  // Skip methods specified by Object.
      }
      if (objectMethods.containsKey(signature)
          && method.getEnclosingElement().getKind() == ElementKind.INTERFACE
          && method.getModifiers().contains(Modifier.ABSTRACT)
          && elements.overrides(method, objectMethods.get(signature), type)) {
        continue;  // Skip abstract methods on interfaces redelaring Object methods.
      }
      Iterator<ExecutableElement> iterator = methods.get(signature).iterator();
      while (iterator.hasNext()) {
        ExecutableElement otherMethod = iterator.next();
        if (elements.overrides(method, otherMethod, type)
            || method.getParameters().equals(otherMethod.getParameters())) {
          iterator.remove();
        }
      }
      methods.put(signature, method);
    }
  }
  return ImmutableSet.copyOf(methods.values());
}
 
Example 8
Source File: RedisShardBackplane.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private SetMultimap<String, String> toMultimap(List<Platform.Property> provisions) {
  SetMultimap<String, String> set = LinkedHashMultimap.create();
  for (Platform.Property property : provisions) {
    set.put(property.getName(), property.getValue());
  }
  return set;
}
 
Example 9
Source File: EventBusPublishingTaskFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public SetMultimap<String, Integer> getEventsSeenMap() {
  SetMultimap<String, Integer> seenEvents = HashMultimap.create();
  for (EventBusPublishingTaskFactory.Event event : this.events) {
    seenEvents.put(event.getType(), event.getId());
  }
  return seenEvents;
}
 
Example 10
Source File: AbstractSearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add a complete Lucene Document based on these statements. Do not search for an existing document with the same
 * subject id. (assume the existing document was deleted)
 *
 * @param statements the statements that make up the resource
 * @throws IOException
 */
@Override
public final synchronized void addDocuments(Resource subject, List<Statement> statements) throws IOException {

	String resourceId = SearchFields.getResourceID(subject);

	SetMultimap<String, Statement> stmtsByContextId = HashMultimap.create();

	String contextId;
	for (Statement statement : statements) {
		contextId = SearchFields.getContextID(statement.getContext());

		stmtsByContextId.put(contextId, statement);
	}

	BulkUpdater batch = newBulkUpdate();
	for (Entry<String, Collection<Statement>> entry : stmtsByContextId.asMap().entrySet()) {
		// create a new document
		String id = SearchFields.formIdString(resourceId, entry.getKey());
		SearchDocument document = newDocument(id, resourceId, entry.getKey());

		for (Statement stmt : entry.getValue()) {
			// determine stuff to store
			addProperty(stmt, document);
		}
		// add it to the index
		batch.add(document);
	}
	batch.end();
}
 
Example 11
Source File: DataBundleLogic.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private void processResponsesAndPopulateMap(Collection<FeedbackResponseAttributes> responses,
        SetMultimap<String, FeedbackResponseAttributes> sessionResponsesMap) {
    for (FeedbackResponseAttributes response : responses) {
        String sessionKey = makeSessionKey(response.feedbackSessionName, response.courseId);
        sessionResponsesMap.put(sessionKey, response);
    }
}
 
Example 12
Source File: EntityListenersService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds an entity listener for a entity of the given class that listens to entity changes
 *
 * @param entityListener entity listener for a entity
 */
public void addEntityListener(String repoFullName, EntityListener entityListener) {
  lock.writeLock().lock();
  try {
    verifyRepoRegistered(repoFullName);
    SetMultimap<Object, EntityListener> entityListeners =
        this.entityListenersByRepo.get(repoFullName);
    entityListeners.put(entityListener.getEntityId(), entityListener);
  } finally {
    lock.writeLock().unlock();
  }
}
 
Example 13
Source File: WaitCoalescer.java    From swift-t with Apache License 2.0 5 votes vote down vote up
private static void findRelocatableBlockingInstructions(Program prog,
        Block block, SetMultimap<Var, InstOrCont> waitMap) {
  for (Statement stmt: block.getStatements()) {
    if (stmt.type() != StatementType.INSTRUCTION) {
      continue; // Only interested in instructions
    }

    Instruction inst = stmt.instruction();
    // check all outputs are non-alias futures - if not can't safely reorder
    boolean canMove = true;
    for (Var out: inst.getOutputs()) {
      if (!Types.isFuture(out) || out.storage() == Alloc.ALIAS) {
        canMove = false;
        break;
      }
    }
    if (canMove) {
      // Put in map based on which inputs will block execution of task
      List<Var> bi = inst.getBlockingInputs(prog);
      if (bi != null) {
        for (Var in: bi) {
          if (trackForPushdown(in)) {
            waitMap.put(in, new InstOrCont(inst));
          }
        }
      }
    }
  }
}
 
Example 14
Source File: VpcCfgReconstruction.java    From jakstab with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fold ART into a map from VPC locations to sets of abstract states, and
 * then flatten the state sets into single abstract states by joining.
 * 
 * @return a map from VPC locations to the join of all abstract states at 
 * that VPC location
 */
private Map<Location, AbstractState> flattenArtOntoVpcLocations() {

	SetMultimap<Location, AbstractState> vpcSensitiveReached = HashMultimap.create();
	
	Deque<AbstractState> worklist = new LinkedList<AbstractState>();
	worklist.add(art.getRoot());
	Set<AbstractState> visited = new HashSet<AbstractState>();
	visited.add(art.getRoot());
	
	while (!worklist.isEmpty()) {
		AbstractState headState = worklist.removeFirst();
		if (isVpcStateBot(headState))
			continue;
		
		BasedNumberElement vpcVal = getVPC(headState);
		VpcLocation headVpcLoc = new VpcLocation(vpcVal, (RTLLabel)headState.getLocation());

		vpcSensitiveReached.put(headVpcLoc, headState);

		Set<Pair<CFAEdge, AbstractState>> successors = art.getChildren(headState);
		for (Pair<CFAEdge, AbstractState> sPair : successors) {
			AbstractState nextState = sPair.getRight();
			
			if (!visited.contains(nextState)) {
				visited.add(nextState);
				worklist.add(nextState);
			}
		}
	}
	
	Map<Location, AbstractState> constants = new HashMap<Location, AbstractState>();
	for (Location l : vpcSensitiveReached.keySet()) {
		constants.put(l, Lattices.joinAll(vpcSensitiveReached.get(l)));
	}
	
	return constants;
}
 
Example 15
Source File: ModuleSplitsToShardMerger.java    From bundletool with Apache License 2.0 4 votes vote down vote up
private ModuleSplit mergeSingleShard(
    ImmutableCollection<ModuleSplit> splitsOfShard,
    BundleMetadata bundleMetadata,
    Map<ImmutableSet<ModuleEntry>, ImmutableList<Path>> mergedDexCache,
    SplitType mergedSplitType,
    AndroidManifestMerger manifestMerger) {

  ListMultimap<BundleModuleName, ModuleEntry> dexFilesToMergeByModule =
      ArrayListMultimap.create();
  // If multiple splits were generated from one module, we'll see the same manifest multiple
  // times. The multimap filters out identical (module name, manifest) pairs by contract.
  // All splits of a module should have the same manifest, so the following multimap should
  // associate just one value with each key. This is checked explicitly for the base module
  // because the manifest merger requires *single* base manifest.
  SetMultimap<BundleModuleName, AndroidManifest> androidManifestsToMergeByModule =
      HashMultimap.create();

  Map<ZipPath, ModuleEntry> mergedEntriesByPath = new HashMap<>();
  Optional<ResourceTable> mergedResourceTable = Optional.empty();
  Map<String, TargetedAssetsDirectory> mergedAssetsConfig = new HashMap<>();
  ApkTargeting mergedSplitTargeting = ApkTargeting.getDefaultInstance();

  for (ModuleSplit split : splitsOfShard) {
    // Resource tables and Split targetings can be merged for each split individually as we go.
    mergedResourceTable = mergeResourceTables(mergedResourceTable, split);
    mergedSplitTargeting = mergeSplitTargetings(mergedSplitTargeting, split);

    // Android manifests need to be merged later, globally for all splits.
    androidManifestsToMergeByModule.put(split.getModuleName(), split.getAndroidManifest());

    for (ModuleEntry entry : split.getEntries()) {
      if (entry.getPath().startsWith(DEX_DIRECTORY)) {
        // Dex files need to be merged later, globally for all splits.
        dexFilesToMergeByModule.put(split.getModuleName(), entry);
      } else {
        mergeEntries(mergedEntriesByPath, split, entry);
      }
    }

    split
        .getAssetsConfig()
        .ifPresent(
            assetsConfig -> {
              mergeTargetedAssetsDirectories(mergedAssetsConfig, assetsConfig.getDirectoryList());
            });
  }

  AndroidManifest mergedAndroidManifest = manifestMerger.merge(androidManifestsToMergeByModule);

  Collection<ModuleEntry> mergedDexFiles =
      mergeDexFilesAndCache(
          dexFilesToMergeByModule, bundleMetadata, mergedAndroidManifest, mergedDexCache);

  // Record names of the modules this shard was fused from.
  ImmutableList<String> fusedModuleNames = getUniqueModuleNames(splitsOfShard);
  if (mergedSplitType.equals(SplitType.STANDALONE)) {
    mergedAndroidManifest =
        mergedAndroidManifest.toEditor().setFusedModuleNames(fusedModuleNames).save();
  }

  // Construct the final shard.
  return buildShard(
      mergedEntriesByPath.values(),
      mergedDexFiles,
      mergedSplitTargeting,
      mergedAndroidManifest,
      mergedResourceTable,
      mergedAssetsConfig,
      mergedSplitType);
}
 
Example 16
Source File: AbstractActionState.java    From PeerWasp with MIT License 4 votes vote down vote up
private void putToFolderMoveSources(FolderComposite file) {
	final IFileTree fileTree = action.getFileEventManager().getFileTree();
	SetMultimap<String, FolderComposite> deletedFolders = fileTree.getDeletedByStructureHash();
	logger.trace("Delete folder: put folder {} with structure hash {} to deleted folders.", file.getPath(), file.getStructureHash());
	deletedFolders.put(file.getStructureHash(), (FolderComposite)file);
}
 
Example 17
Source File: DexFileMergerTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
private Multimap<String, String> assertMultidexOutput(int expectedClassCount,
    Path outputArchive, Set<String> mainDexList) throws IOException {
  SetMultimap<String, String> dexFiles = HashMultimap.create();
  try (ZipFile output = new ZipFile(outputArchive.toFile())) {
    Enumeration<? extends ZipEntry> entries = output.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      assertThat(entry.getName()).containsMatch("classes[2-9]?.dex");
      Dex dex = new Dex(output.getInputStream(entry));
      for (ClassDef clazz : dex.classDefs()) {
        dexFiles.put(entry.getName(),
            toSlashedClassName(dex.typeNames().get(clazz.getTypeIndex())));
      }
    }
  }
  assertThat(dexFiles.keySet().size()).isAtLeast(2); // test sanity
  assertThat(dexFiles.size()).isAtLeast(1); // test sanity
  assertThat(dexFiles).hasSize(expectedClassCount);
  for (int i = 0; i < dexFiles.keySet().size(); ++i) {
    assertThat(dexFiles).containsKey(expectedDexFileName(i));
  }
  for (int i = 1; i < dexFiles.keySet().size(); ++i) {
    Set<String> prev = dexFiles.get(expectedDexFileName(i - 1));
    if (i == 1) {
      prev = Sets.difference(prev, mainDexList);
    }
    Set<String> shard = dexFiles.get(expectedDexFileName(i));
    for (String c1 : prev) {
      for (String c2 : shard) {
        assertWithMessage(
                c2
                    + " in shard "
                    + i
                    + " should compare as larger than "
                    + c1
                    + "; list of all shards for reference: "
                    + dexFiles)
            .that(ZipEntryComparator.compareClassNames(c2, c1))
            .isGreaterThan(0);
      }
    }
  }
  return dexFiles;
}
 
Example 18
Source File: NodeLabelPart.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected SetMultimap<? extends Object, String> doGetContentAnchorages() {
	SetMultimap<Object, String> contentAnchorages = HashMultimap.create();
	contentAnchorages.put(getContent().getKey(), getContent().getValue());
	return contentAnchorages;
}
 
Example 19
Source File: SetMultimapExpression.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean put(K key, V value) {
	final SetMultimap<K, V> setMultimap = get();
	return (setMultimap == null) ? EMPTY_SETMULTIMAP.put(key, value)
			: setMultimap.put(key, value);
}
 
Example 20
Source File: ObservableListWrapperEx.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Sorts the elements of this {@link ObservableListWrapperEx} using the
 * given {@link Comparator}.
 *
 * @param c
 *            The {@link Comparator} to use.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sort(Comparator<? super E> c) {
	// TODO: This algorithm is not very elaborated, as computation of
	// permutation indexes is done independent of the sort itself, and we
	// need to iterate over the complete list to compute the previous
	// indexes (so we can properly handle elements with multiple
	// occurrences).
	List<E> previousContents = delegateCopy();
	SetMultimap<E, Integer> previousIndexes = HashMultimap.create();
	for (int i = 0; i < previousContents.size(); i++) {
		previousIndexes.put(previousContents.get(i), i);
	}

	// List.sort(Comparator) was introduced in 1.8; we use list iterator
	// directly here, so we stay compatible with 1.7
	// TODO: change to using List.sort(Comparator) when dropping support for
	// JavaSE-1.7.
	Object[] a = delegate().toArray();
	int[] permutation = new int[a.length];
	Arrays.sort(a, (Comparator) c);
	ListIterator<E> iterator = delegate().listIterator();
	// keep track if list was actually changed
	boolean changed = false;
	for (int i = 0; i < a.length; i++) {
		E current = iterator.next();
		if (current != a[i]) {
			changed = true;
			iterator.set((E) a[i]);
		}
		// build-up permutation (for change notification)
		Iterator<Integer> previousIndexIterator = previousIndexes
				.get((E) a[i]).iterator();
		permutation[previousIndexIterator.next()] = i;
		previousIndexIterator.remove();
	}
	if (changed) {
		helper.fireValueChangedEvent(
				new ListListenerHelperEx.AtomicChange<>(this,
						previousContents,
						ListListenerHelperEx.ElementarySubChange
								.<E> permutated(permutation, 0, a.length)));
	}
}