com.google.common.collect.SetMultimap Java Examples

The following examples show how to use com.google.common.collect.SetMultimap. 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: TaskSelector.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public TaskSelection getSelection(String path) {
    SetMultimap<String, TaskSelectionResult> tasksByName;
    ProjectInternal project = gradle.getDefaultProject();
    ResolvedTaskPath taskPath = taskPathResolver.resolvePath(path, project);

    if (taskPath.isQualified()) {
        tasksByName = taskNameResolver.select(taskPath.getTaskName(), taskPath.getProject());
    } else {
        tasksByName = taskNameResolver.selectAll(taskPath.getTaskName(), taskPath.getProject());
    }

    Set<TaskSelectionResult> tasks = tasksByName.get(taskPath.getTaskName());
    if (!tasks.isEmpty()) {
        // An exact match
        return new TaskSelection(path, tasks);
    }

    NameMatcher matcher = new NameMatcher();
    String actualName = matcher.find(taskPath.getTaskName(), tasksByName.keySet());
    if (actualName != null) {
        return new TaskSelection(taskPath.getPrefix() + actualName, tasksByName.get(actualName));
    }

    throw new TaskSelectionException(matcher.formatErrorMessage("task", taskPath.getProject()));
}
 
Example #2
Source File: TargetedEventBusImpl.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
@Inject TargetedEventBusImpl(ExceptionHandler exceptionHandler, EventRegistry eventRegistry, TargetedEventHandlerScanner eventHandlerScanner, TypeMap<Object, TargetedEventRouter<?>> routers) {
    this.exceptionHandler = exceptionHandler;
    this.eventRegistry = eventRegistry;
    this.routers = routers;

    // Cache of handler methods per listener type
    this.listenerCache = CacheUtils.newCache(listener -> {
        final SetMultimap<EventKey<? extends Event>, EventHandlerInfo<? extends Event>> handlers = eventHandlerScanner.findEventHandlers(listener);
        for(EventHandlerInfo<? extends Event> info : handlers.values()) {
            if(this.routers.allAssignableFrom(info.event()).isEmpty()) {
                throw new InvalidMemberException(
                    info.method(),
                    "No router registered for targeted event type " + info.event().getName()
                );
            }
        }
        return handlers;
    });
}
 
Example #3
Source File: ReferenceValidatorImpl.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeNode(Object obj, DescriptorPath path) {
  Preconditions.checkState(!refsStack.containsKey(path));

  SetMultimap<ReferenceType, String> refs = getRelatedPaths(obj, path);
  SetMultimap<ReferenceType, String> newRefs = LinkedHashMultimap.create();

  for (Map.Entry<ReferenceType, Collection<String>> entry : refs.asMap().entrySet()) {
    ReferenceType type = entry.getKey();
    for (String reference : entry.getValue()) {
      if (!allowedRefs.containsEntry(type, reference)) {
        newRefs.put(type, reference);
        allowedRefs.put(type, reference);
      }
    }
  }

  // consolidate into the singleton if it's empty
  newRefs = newRefs.size() == 0 ? ImmutableSetMultimap
      .<ReferenceType, String> of() : newRefs;
  refsStack.put(path, newRefs);

  callReferenceConstraints(obj, path);
}
 
Example #4
Source File: ClasspathCache.java    From glowroot with Apache License 2.0 6 votes vote down vote up
synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap =
                MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}
 
Example #5
Source File: FunctionFeed.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected void preStart() {
    SetMultimap<FunctionPollIdentifier, FunctionPollConfig<?, ?>> polls = getConfig(POLLS);
    for (final FunctionPollIdentifier pollInfo : polls.keySet()) {
        Set<FunctionPollConfig<?,?>> configs = polls.get(pollInfo);
        long minPeriod = Integer.MAX_VALUE;
        Set<AttributePollHandler<?>> handlers = Sets.newLinkedHashSet();

        for (FunctionPollConfig<?,?> config : configs) {
            handlers.add(new AttributePollHandler(config, entity, this));
            if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod());
        }
        
        getPoller().scheduleAtFixedRate(
                (Callable)pollInfo.job,
                new DelegatingPollHandler(handlers), 
                minPeriod);
    }
}
 
Example #6
Source File: UniformNodeSelector.java    From presto with Apache License 2.0 6 votes vote down vote up
/**
 * The method selects and removes a split from the fromNode and assigns it to the toNode. There is an attempt to
 * redistribute a Non-local split if possible. This case is possible when there are multiple queries running
 * simultaneously. If a Non-local split cannot be found in the maxNode, any split is selected randomly and reassigned.
 */
@VisibleForTesting
public static void redistributeSplit(Multimap<InternalNode, Split> assignment, InternalNode fromNode, InternalNode toNode, SetMultimap<InetAddress, InternalNode> nodesByHost)
{
    Iterator<Split> splitIterator = assignment.get(fromNode).iterator();
    Split splitToBeRedistributed = null;
    while (splitIterator.hasNext()) {
        Split split = splitIterator.next();
        // Try to select non-local split for redistribution
        if (!split.getAddresses().isEmpty() && !isSplitLocal(split.getAddresses(), fromNode.getHostAndPort(), nodesByHost)) {
            splitToBeRedistributed = split;
            break;
        }
    }
    // Select any split if maxNode has no non-local splits in the current batch of assignment
    if (splitToBeRedistributed == null) {
        splitIterator = assignment.get(fromNode).iterator();
        splitToBeRedistributed = splitIterator.next();
    }
    splitIterator.remove();
    assignment.put(toNode, splitToBeRedistributed);
}
 
Example #7
Source File: DisableDamageModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public static DisableDamageModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException {
    SetMultimap<DamageCause, PlayerRelation> causes = HashMultimap.create();
    for(Element damageCauseElement : doc.getRootElement().getChildren("disabledamage")) {
        for(Element damageEl : damageCauseElement.getChildren("damage")) {
            DamageCause cause = XMLUtils.parseEnum(damageEl, DamageCause.class, "damage type");
            for(PlayerRelation damagerType : PlayerRelation.values()) {
                // Legacy syntax used "other" instead of "neutral"
                String attrName = damagerType.name().toLowerCase();
                Node attr = damagerType == PlayerRelation.NEUTRAL ? Node.fromAttr(damageEl, attrName, "other")
                                                                  : Node.fromAttr(damageEl, attrName);
                if(XMLUtils.parseBoolean(attr, true)) {
                    causes.put(cause, damagerType);

                    // Bukkit 1.7.10 changed TNT from BLOCK_EXPLOSION to ENTITY_EXPLOSION,
                    // so we include them both to keep old maps working.
                    if(cause == DamageCause.BLOCK_EXPLOSION) {
                        causes.put(DamageCause.ENTITY_EXPLOSION, damagerType);
                    }
                }
            }
        }
    }
    return new DisableDamageModule(causes);
}
 
Example #8
Source File: SetMultimapPropertyTest.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet_returnsLiveView() {
  behaviorTester
      .with(new Processor(features))
      .with(dataType)
      .with(testBuilder()
          .addLine("DataType.Builder builder = new DataType.Builder();")
          .addLine("%s<%s, %s> itemsView = builder.%s;",
              SetMultimap.class, key.type(), value.type(), convention.get("items"))
          .addLine("assertThat(itemsView).isEmpty();")
          .addLine("builder.putItems(%s, %s);", key.example(0), value.example(1))
          .addLine("assertThat(itemsView).contains(%s, %s).andNothingElse();",
              key.example(0), value.example(1))
          .addLine("builder.clearItems();")
          .addLine("assertThat(itemsView).isEmpty();")
          .addLine("builder.putItems(%s, %s);", key.example(2), value.example(3))
          .addLine("assertThat(itemsView).contains(%s, %s).andNothingElse();",
              key.example(2), value.example(3))
          .build())
      .runTest();
}
 
Example #9
Source File: Consultant.java    From consultant with Apache License 2.0 6 votes vote down vote up
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, long whenLocatingServicesCacheResultsFor) {

	this.registered = new AtomicBoolean();
	this.settingListeners = Multimaps.synchronizedSetMultimap(settingListeners);
	this.configListeners = Sets.newConcurrentHashSet(configListeners);
	this.serviceInstanceBackend = new ServiceInstanceBackend(identifier.getDatacenter(), consulUri, mapper, http,
			whenLocatingServicesCacheResultsFor);

	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;
}
 
Example #10
Source File: WorkerQueuesTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void gpuConfig_validProvisionsEnqueued() {

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

  // Act
  Operation operation = Operation.newBuilder().build();
  SetMultimap<String, String> provisions = HashMultimap.create();
  provisions.put("foo", "bar");
  provisions.put("gpu_required", "only key matters");
  provisions.put("another", "provision");
  boolean success = queues.enqueueOperation(operation, provisions);

  // Assert
  assertThat(success).isTrue();
  assertThat(queues.queueSize("GPU")).isEqualTo(1);
}
 
Example #11
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 #12
Source File: SchemaContextFactoryDeviationsTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static ListenableFuture<EffectiveModelContext> createSchemaContext(
        final SetMultimap<QNameModule, QNameModule> modulesWithSupportedDeviations, final String... resources)
        throws Exception {
    final SharedSchemaRepository sharedSchemaRepository = new SharedSchemaRepository(
            "shared-schema-repo-with-deviations-test");

    final Collection<SourceIdentifier> requiredSources = new ArrayList<>();
    for (final String resource : resources) {
        final SettableSchemaProvider<ASTSchemaSource> yangSource = getImmediateYangSourceProviderFromResource(
                resource);
        yangSource.register(sharedSchemaRepository);
        yangSource.setResult();
        requiredSources.add(yangSource.getId());
    }

    final SchemaContextFactoryConfiguration config = SchemaContextFactoryConfiguration.builder()
            .setModulesDeviatedByModules(modulesWithSupportedDeviations).build();
    return sharedSchemaRepository.createEffectiveModelContextFactory(config).createEffectiveModelContext(
        requiredSources);
}
 
Example #13
Source File: ConditionalEdges.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Builds ConditionalEdges from given graph. */
public ConditionalEdges(Digraph<Target> graph) {
  this.map = new HashMap<>();

  for (Node<Target> node : graph.getNodes()) {
    Rule rule = node.getLabel().getAssociatedRule();
    if (rule == null) {
      // rule is null for source files and package groups. Skip them.
      continue;
    }

    SetMultimap<Label, Label> conditions = getAllConditions(rule, RawAttributeMapper.of(rule));
    if (conditions.isEmpty()) {
      // bail early for most common case of no conditions in the rule.
      continue;
    }

    Label nodeLabel = node.getLabel().getLabel();
    for (Node<Target> succ : node.getSuccessors()) {
      Label successorLabel = succ.getLabel().getLabel();
      if (conditions.containsKey(successorLabel)) {
        insert(nodeLabel, successorLabel, conditions.get(successorLabel));
      }
    }
  }
}
 
Example #14
Source File: ChoiceCavGenerator.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@Override
public List<CandidateAnswerVariant> generate(JCas jcas) throws AnalysisEngineProcessException {
  List<Token> tokens = TypeUtil.getOrderedTokens(jcas);
  SetMultimap<Token, Token> head2children = CavUtil.getHeadTokenMap(tokens);
  Token orToken;
  try {
    orToken = tokens.stream().filter(t -> OR_LEMMA.equals(t.getLemmaForm())).findAny().get();
  } catch (NoSuchElementException e) {
    return new ArrayList<>();
  }
  // identify head tokens for choices from the question
  Token mainToken = orToken.getHead();
  List<Token> alternativeTokens = head2children.get(mainToken).stream()
          .filter(t -> CONJ_DEP_LABEL.equals(t.getDepLabel())).collect(toList());
  List<CandidateAnswerVariant> cavs = Stream
          .concat(Stream.of(mainToken), alternativeTokens.stream())
          .map(token -> CavUtil.createCandidateAnswerVariant(jcas, token)).collect(toList());
  // find CAVs from evidence passages
  Stream.concat(Stream.of(mainToken), alternativeTokens.stream())
          .map(token -> JCasUtil.selectCovering(ConceptMention.class, token))
          .flatMap(Collection::stream).map(ConceptMention::getConcept)
          .map(concept -> CavUtil.createCandidateAnswerVariant(jcas, concept)).forEach(cavs::add);
  return cavs;
}
 
Example #15
Source File: Environment.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private static void getLocalAndInheritedMethods(PackageElement pkg,
                                                TypeElement type,
                                                SetMultimap<String, ExecutableElement> methods,
                                                ConditionCallback<ExecutableElement> includeMethodCallback) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    final TypeElement superInterfaceElement = asTypeElement(superInterface);
    final String interfaceName = superInterfaceElement.getSimpleName().toString();
    if (interfaceName.startsWith("Parcelable")) continue;

    getLocalAndInheritedMethods(pkg, superInterfaceElement, methods, includeMethodCallback);
  }
  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.
    getLocalAndInheritedMethods(pkg, asTypeElement(type.getSuperclass()), methods, includeMethodCallback);
  }
  for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) {
    if (includeMethodCallback.call(method)
        && visibleFromPackage(method, pkg)) {
      methods.put(method.getSimpleName().toString(), method);
    }
  }
}
 
Example #16
Source File: IpsecUtil.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all {@link IpsecPeerConfigId}s whose local IP is equal to any of the IPs behind
 * destinationIp after NAT
 */
@Nonnull
private static Set<IpsecPeerConfigId> getCandidatePeersBehindNat(
    @Nonnull Ip destinationIp,
    @Nonnull SetMultimap<Ip, IpWildcardSetIpSpace> privateIpsByPublicIp,
    @Nonnull Map<Ip, Set<IpsecPeerConfigId>> localIpsAndIpsecPeers) {
  ImmutableSet.Builder<IpsecPeerConfigId> candidateNeighbors = ImmutableSet.builder();
  Set<IpWildcardSetIpSpace> privateIpsBehindDestIp = privateIpsByPublicIp.get(destinationIp);
  if (privateIpsBehindDestIp == null) {
    return candidateNeighbors.build();
  }
  for (IpWildcardSetIpSpace ipWildcardSetIpSpace : privateIpsBehindDestIp) {
    for (Entry<Ip, Set<IpsecPeerConfigId>> entry : localIpsAndIpsecPeers.entrySet()) {
      if (ipWildcardSetIpSpace.containsIp(entry.getKey(), ImmutableMap.of())) {
        candidateNeighbors.addAll(entry.getValue());
      }
    }
  }
  return candidateNeighbors.build();
}
 
Example #17
Source File: ShardWorkerContext.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
static SetMultimap<String, String> getMatchProvisions(
    Platform platform, Iterable<ExecutionPolicy> policyNames, int executeStageWidth) {
  ImmutableSetMultimap.Builder<String, String> provisions = ImmutableSetMultimap.builder();
  for (Platform.Property property : platform.getPropertiesList()) {
    provisions.put(property.getName(), property.getValue());
  }
  for (ExecutionPolicy policy : policyNames) {
    String name = policy.getName();
    if (!name.isEmpty()) {
      provisions.put("execution-policy", name);
    }
  }
  provisions.put("cores", String.format("%d", executeStageWidth));
  return provisions.build();
}
 
Example #18
Source File: SetMultimapExpression.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Set<V> replaceValues(K key, Iterable<? extends V> values) {
	final SetMultimap<K, V> setMultimap = get();
	return (setMultimap == null)
			? EMPTY_SETMULTIMAP.replaceValues(key, values)
			: setMultimap.replaceValues(key, values);
}
 
Example #19
Source File: WorkerQueues.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private Boolean QueueIsEligible(WorkerQueue queue, SetMultimap<String, String> provisions) {
  for (String checkedProvision : queue.requiredProvisions.asMap().keySet()) {
    if (!provisions.asMap().containsKey(checkedProvision)) {
      return false;
    }
  }
  return true;
}
 
Example #20
Source File: TreeFinder.java    From annotation-tools with MIT License 5 votes vote down vote up
/**
 * Scans the given tree with the given {@link Insertions} and returns
 * the mapping from source position to insertion text.
 *
 * <p>
 * <i>N.B.:</i> This method calls {@code scan()} internally.
 * </p>
 *
 * @param node the tree to scan
 * @param insertions the insertion criteria
 * @return the source position to insertion text mapping
 */
public SetMultimap<Pair<Integer, ASTPath>, Insertion>
getPositions(JCCompilationUnit node, Insertions insertions) {
  List<Insertion> list = new ArrayList<>();
  treePathCache.clear();
  if (annotator.Main.temporaryDebug) {
    System.out.println("insertions size: " + insertions.size());
    System.out.println("insertions.forOuterClass(\"\") size: " + insertions.forOuterClass(node, "").size());
    System.out.println("list pre-size: " + list.size());
  }
  list.addAll(insertions.forOuterClass(node, ""));
  if (annotator.Main.temporaryDebug) {
    System.out.println("list post-size: " + list.size());
  }
  for (JCTree decl : node.getTypeDecls()) {
    if (decl.getTag() == JCTree.Tag.CLASSDEF) {
      String name = ((JCClassDecl) decl).sym.className();
      Collection<Insertion> forClass = insertions.forOuterClass(node, name);
      if (annotator.Main.temporaryDebug) {
        System.out.println("insertions size: " + insertions.size());
        System.out.println("insertions.forOuterClass("+name+") size: " + forClass.size());
        System.out.println("list pre-size: " + list.size());
      }
      list.addAll(forClass);
      if (annotator.Main.temporaryDebug) {
        System.out.println("list post-size: " + list.size());
      }
    }
  }
  return getInsertionsByPosition(node, list);
}
 
Example #21
Source File: PluginManager.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
private static void buildPluginNames(SetMultimap<String, Class<?>> info, Properties properties) {

    for (String name : properties.stringPropertyNames()) {

      List<Class<?>> classList = classList(name, properties.getProperty(name));
      if (info.containsKey(name)) {

        throw new GenerationException("duplicate name in plugins: " + name);
      }
      info.putAll(name, classList);
    }
  }
 
Example #22
Source File: ObservableSetMultimapTests.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void putAll_singleKey() {
	// prepare backup map
	SetMultimap<Integer, String> backupMap = HashMultimap.create();
	check(observable, backupMap);

	// register listeners
	registerListeners();

	// add two new distinct values
	invalidationListener.expect(1);
	setMultimapChangeListener.addAtomicExpectation();
	setMultimapChangeListener.addElementaryExpectation(1,
			Collections.<String> emptySet(), Sets.newHashSet("1-1", "1-2"));
	assertEquals(backupMap.putAll(1, Arrays.asList("1-1", "1-2")),
			observable.putAll(1, Arrays.asList("1-1", "1-2")));
	check(observable, backupMap);
	checkListeners();

	// add a new and an already added value
	invalidationListener.expect(1);
	setMultimapChangeListener.addAtomicExpectation();
	setMultimapChangeListener.addElementaryExpectation(1,
			Collections.<String> emptySet(), Sets.newHashSet("1-3"));
	assertEquals(backupMap.putAll(1, Arrays.asList("1-2", "1-3")),
			observable.putAll(1, Arrays.asList("1-2", "1-3")));
	check(observable, backupMap);
	checkListeners();

	// put already added values
	assertEquals(backupMap.putAll(1, Arrays.asList("1-2", "1-3")),
			observable.putAll(1, Arrays.asList("1-2", "1-3")));
	check(observable, backupMap);
	checkListeners();
}
 
Example #23
Source File: MoreElements.java    From auto with Apache License 2.0 5 votes vote down vote up
private static void getAllMethods(
    TypeElement type, SetMultimap<String, ExecutableElement> methods) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    getAllMethods(MoreTypes.asTypeElement(superInterface), methods);
  }
  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.
    getAllMethods(MoreTypes.asTypeElement(type.getSuperclass()), methods);
  }
  for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) {
    methods.put(method.getSimpleName().toString(), method);
  }
}
 
Example #24
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 #25
Source File: FlumeEventQueue.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
/**
 * Read the inflights file and return a
 * {@link com.google.common.collect.SetMultimap}
 * of transactionIDs to events that were inflight.
 *
 * @return - map of inflight events per txnID.
 *
 */
public SetMultimap<Long, Long> deserialize()
        throws IOException, BadCheckpointException {
  SetMultimap<Long, Long> inflights = HashMultimap.create();
  if (!fileChannel.isOpen()) {
    file = new RandomAccessFile(inflightEventsFile, "rw");
    fileChannel = file.getChannel();
  }
  if(file.length() == 0) {
    return inflights;
  }
  file.seek(0);
  byte[] checksum = new byte[16];
  file.read(checksum);
  ByteBuffer buffer = ByteBuffer.allocate(
          (int)(file.length() - file.getFilePointer()));
  fileChannel.read(buffer);
  byte[] fileChecksum = digest.digest(buffer.array());
  if (!Arrays.equals(checksum, fileChecksum)) {
    throw new BadCheckpointException("Checksum of inflights file differs"
            + " from the checksum expected.");
  }
  buffer.position(0);
  LongBuffer longBuffer = buffer.asLongBuffer();
  try {
    while (true) {
      long txnID = longBuffer.get();
      int numEvents = (int)(longBuffer.get());
      for(int i = 0; i < numEvents; i++) {
        long val = longBuffer.get();
        inflights.put(txnID, val);
      }
    }
  } catch (BufferUnderflowException ex) {
    LOG.debug("Reached end of inflights buffer. Long buffer position ="
            + String.valueOf(longBuffer.position()));
  }
  return  inflights;
}
 
Example #26
Source File: DefaultDockerCmdExecFactory.java    From docker-java with Apache License 2.0 5 votes vote down vote up
DefaultWebTarget(
    ImmutableList<String> path,
    SetMultimap<String, String> queryParams
) {
    this.path = path;
    this.queryParams = queryParams;
}
 
Example #27
Source File: ObservableSetMultimapTests.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void clear() {
	// initialize maps with some values
	observable.putAll(1, Sets.newHashSet("1-1", "1-2", "1-3"));
	observable.putAll(2, Sets.newHashSet("2-1", "2-2", "2-3"));
	observable.putAll(null, Sets.newHashSet(null, "null"));

	// prepare backup map
	SetMultimap<Integer, String> backupMap = HashMultimap.create();
	backupMap.putAll(1, Sets.newHashSet("1-1", "1-2", "1-3"));
	backupMap.putAll(2, Sets.newHashSet("2-1", "2-2", "2-3"));
	backupMap.putAll(null, Sets.newHashSet(null, "null"));
	check(observable, backupMap);

	registerListeners();

	// remove all values
	invalidationListener.expect(1);
	setMultimapChangeListener.addAtomicExpectation();
	setMultimapChangeListener.addElementaryExpectation(null,
			Sets.newHashSet(null, "null"), Collections.<String> emptySet());
	setMultimapChangeListener.addElementaryExpectation(1,
			Sets.newHashSet("1-1", "1-2", "1-3"),
			Collections.<String> emptySet());
	setMultimapChangeListener.addElementaryExpectation(2,
			Sets.newHashSet("2-1", "2-2", "2-3"),
			Collections.<String> emptySet());
	observable.clear();
	backupMap.clear();
	check(observable, backupMap);
	checkListeners();

	// clear again (while already empty)
	invalidationListener.expect(0);
	observable.clear();
	backupMap.clear();
	check(observable, backupMap);
	checkListeners();
}
 
Example #28
Source File: ExtendsTagTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void itHasExtendsReferenceInContext() throws Exception {
  RenderResult renderResult = jinjava.renderForResult(
    locator.fixture("super-child.html"),
    new HashMap<String, Object>()
  );
  SetMultimap<String, String> dependencies = renderResult
    .getContext()
    .getDependencies();

  assertThat(dependencies.size()).isEqualTo(1);
  assertThat(dependencies.get("coded_files")).isNotEmpty();

  assertThat(dependencies.get("coded_files").contains("super-base.html"));
}
 
Example #29
Source File: FusingAndroidManifestMergerTest.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Test
public void merge_featureActivitiesIntoBaseManifest() {
  SetMultimap<BundleModuleName, AndroidManifest> manifests =
      createManifests(
          androidManifest(
              "com.testapp",
              withCustomThemeActivity("activity1", BASE_THEME_REF_ID),
              withCustomThemeActivity("activity2", BASE_THEME_REF_ID),
              withCustomThemeActivity("activity3", BASE_THEME_REF_ID)),
          androidManifestForFeature(
              "com.testapp.feature1",
              withCustomThemeActivity("activity1", FEATURE1_THEME_REF_ID)),
          androidManifestForFeature(
              "com.testapp.feature2",
              withCustomThemeActivity("activity3", FEATURE2_THEME_REF_ID)));

  AndroidManifest merged = merger.merge(manifests);

  Map<String, Integer> refIdByActivity =
      Maps.transformValues(
          merged.getActivitiesByName(),
          activity -> activity.getAndroidAttribute(THEME_RESOURCE_ID).get().getValueAsRefId());

  assertThat(merged.getPackageName()).isEqualTo("com.testapp");
  assertThat(refIdByActivity)
      .containsExactly(
          "activity1",
          FEATURE1_THEME_REF_ID,
          "activity2",
          BASE_THEME_REF_ID,
          "activity3",
          FEATURE2_THEME_REF_ID);
}
 
Example #30
Source File: DefaultDockerCmdExecFactory.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DefaultWebTarget queryParamsSet(String name, Set<?> values) {
    SetMultimap<String, String> newQueryParams = HashMultimap.create(queryParams);
    newQueryParams.replaceValues(name, values.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.toSet()));

    return new DefaultWebTarget(path, newQueryParams);
}