Java Code Examples for com.google.common.collect.ListMultimap#containsKey()

The following examples show how to use com.google.common.collect.ListMultimap#containsKey() . 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: HttpRequestExecutors.java    From caravan with Apache License 2.0 6 votes vote down vote up
public static <T> T execute(CloseableHttpClient client, String uri, String method, ListMultimap<String, String> headers, RequestConfig config, Object data,
        StreamSerializer serializer, boolean gzipped, 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, gzipped);
    return execute(client, request, serializer, clazz);
}
 
Example 2
Source File: HttpRequestExecutors.java    From caravan with Apache License 2.0 6 votes vote down vote up
public static String executeString(CloseableHttpClient client, String uri, String method, ListMultimap<String, String> headers, RequestConfig config,
        Object data, StreamSerializer serializer, boolean gzipped) {
    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, gzipped);
    return executeString(client, request);
}
 
Example 3
Source File: HttpAsyncRequestExecutors.java    From caravan with Apache License 2.0 6 votes vote down vote up
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 4
Source File: SageApplication.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private ListMultimap<Chromosome, GenomeRegion> panelWithHotspots(@NotNull final ListMultimap<Chromosome, VariantHotspot> hotspots)
        throws IOException {
    final ListMultimap<Chromosome, GenomeRegion> initialPanel = readPanel(config.panelBed());
    final ListMultimap<Chromosome, GenomeRegion> result = ArrayListMultimap.create();

    for (HumanChromosome chromosome : HumanChromosome.values()) {
        final GenomeRegions builder = new GenomeRegions(chromosome.toString());
        if (initialPanel.containsKey(chromosome)) {
            initialPanel.get(chromosome).forEach(x -> builder.addRegion(x.start(), x.end()));
        }
        if (hotspots.containsKey(chromosome)) {
            hotspots.get(chromosome).forEach(x -> builder.addPosition(x.position()));
        }

        result.putAll(chromosome, builder.build());
    }

    return result;
}
 
Example 5
Source File: DispatchHelper.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Computes all the dispatch methods that are declared in the given type or altered
 * by additional cases in this type. The associated operations are sorted by according their parameter types
 * from left to right where the most special types occur before more common types. Ambiguous
 * ordering is resolved alphabetically.
 * 
    * An exemplary order would look like this
 * <pre>
 *   method(String)
 *   method(Serializable)
 *   method(CharSequence)
 *   method(Object)
 * </pre>
 * 
 * @return a mapping from {@link DispatchSignature signature} to sorted operations.
 */
public ListMultimap<DispatchSignature, JvmOperation> getDeclaredOrEnhancedDispatchMethods(JvmDeclaredType type) {
	ListMultimap<DispatchSignature, JvmOperation> result = Multimaps2.newLinkedHashListMultimap(2,4);
	Iterable<JvmOperation> operations = type.getDeclaredOperations();
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type);
	ContextualVisibilityHelper contextualVisibilityHelper = new ContextualVisibilityHelper(visibilityHelper, owner.newParameterizedTypeReference(type));
	for(JvmOperation operation: operations) {
		if (isDispatchFunction(operation)) {
			DispatchSignature signature = new DispatchSignature(operation.getSimpleName().substring(1), operation.getParameters().size());
			if (!result.containsKey(signature)) {
				List<JvmOperation> allOperations = getAllDispatchMethods(signature, type,
						contextualVisibilityHelper);
				result.putAll(signature, allOperations);
			}
		}
	}
	return result;
}
 
Example 6
Source File: WorldRetrogen.java    From simpleretrogen with GNU General Public License v3.0 6 votes vote down vote up
private void completeRetrogen(ChunkPos chunkCoords, World world, String retroClass)
{
    ListMultimap<ChunkPos, String> pendingMap = pendingWork.get(world);
    if (pendingMap != null && pendingMap.containsKey(chunkCoords))
    {
        pendingMap.remove(chunkCoords, retroClass);
    }

    getSemaphoreFor(world).acquireUninterruptibly();
    try
    {
        ListMultimap<ChunkPos, String> completedMap = completedWork.get(world);
        if (completedMap == null)
        {
            completedMap = ArrayListMultimap.create();
            completedWork.put(world, completedMap);
        }

        completedMap.put(chunkCoords, retroClass);
    }
    finally
    {
        getSemaphoreFor(world).release();
    }
}
 
Example 7
Source File: Transaction.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static void addProtobufChildEntries(TraceEntryImpl entry,
        ListMultimap<TraceEntryImpl, TraceEntryImpl> parentChildMap, long transactionStartTick,
        long captureTick, int depth, TraceEntryVisitor entryVisitor,
        SharedQueryTextCollection sharedQueryTextCollection, boolean removeSingleAuxEntry) {
    if (!parentChildMap.containsKey(entry)) {
        // check containsKey to avoid creating garbage empty list via ListMultimap
        return;
    }
    Collection<TraceEntryImpl> childEntries = parentChildMap.get(entry);
    for (TraceEntryImpl childEntry : childEntries) {
        boolean singleAuxEntry = childEntries.size() == 1 && childEntry.isAuxThreadRoot()
                && !childEntry.hasLocationStackTrace();
        if (singleAuxEntry && removeSingleAuxEntry) {
            addProtobufChildEntries(childEntry, parentChildMap, transactionStartTick,
                    captureTick, depth, entryVisitor, sharedQueryTextCollection,
                    removeSingleAuxEntry);
        } else {
            childEntry.accept(depth, transactionStartTick, captureTick, entryVisitor,
                    sharedQueryTextCollection);
            addProtobufChildEntries(childEntry, parentChildMap, transactionStartTick,
                    captureTick, depth + 1, entryVisitor, sharedQueryTextCollection, false);
        }
    }
}
 
Example 8
Source File: ConfigExpander.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * If --enable_platform_specific_config is true and the corresponding config definition exists, we
 * should enable the platform specific config.
 */
private static boolean shouldEnablePlatformSpecificConfig(
    OptionValueDescription enablePlatformSpecificConfigDescription,
    ListMultimap<String, RcChunkOfArgs> commandToRcArgs,
    List<String> commandsToParse) {
  if (enablePlatformSpecificConfigDescription == null
      || !(boolean) enablePlatformSpecificConfigDescription.getValue()) {
    return false;
  }

  for (String commandName : commandsToParse) {
    String defaultConfigDef = commandName + ":" + getPlatformName();
    if (commandToRcArgs.containsKey(defaultConfigDef)) {
      return true;
    }
  }
  return false;
}
 
Example 9
Source File: ClusterFactory.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private ListMultimap<Chromosome, Cluster> cluster(@NotNull final Multimap<Chromosome, SVSegment> variantPositions,
        @NotNull final Multimap<Chromosome, PCFPosition> pcfPositions, @NotNull final ListMultimap<Chromosome, CobaltRatio> ratios) {
    ListMultimap<Chromosome, Cluster> clusters = ArrayListMultimap.create();
    for (Chromosome chromosome : pcfPositions.keySet()) {
        final Collection<PCFPosition> chromosomePcfPositions = pcfPositions.get(chromosome);
        final List<CobaltRatio> chromosomeRatios = ratios.containsKey(chromosome) ? ratios.get(chromosome) : Lists.newArrayList();
        final Collection<SVSegment> chromosomeVariants =
                variantPositions.containsKey(chromosome) ? variantPositions.get(chromosome) : Lists.newArrayList();
        clusters.putAll(chromosome, cluster(chromosomeVariants, chromosomePcfPositions, chromosomeRatios));
    }

    return clusters;
}
 
Example 10
Source File: ProductPartitionTreeImpl.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Using the criteria in {@code parentIdMap}, recursively adds all children under the partition ID
 * of {@code parentNode} to {@code parentNode}.
 *
 * @param parentNode required
 * @param parentIdMap the multimap from parent partition ID to list of child criteria
 */
private static void addChildNodes(ProductPartitionNode parentNode,
    ListMultimap<Long, AdGroupCriterion> parentIdMap) {
  if (parentIdMap.containsKey(parentNode.getProductPartitionId())) {
    parentNode = parentNode.asSubdivision();
  }
  for (AdGroupCriterion adGroupCriterion : parentIdMap.get(parentNode.getProductPartitionId())) {
    ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
    ProductPartitionNode childNode = parentNode.addChild(partition.getCaseValue());
    childNode = childNode.setProductPartitionId(partition.getId());
    if (ProductPartitionType.SUBDIVISION.equals(partition.getPartitionType())) {
      childNode = childNode.asSubdivision();
    } else {
      if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
        childNode = childNode.asBiddableUnit();
        BiddableAdGroupCriterion biddableAdGroupCriterion =
            (BiddableAdGroupCriterion) adGroupCriterion;
        Money cpcBidAmount = getBid(biddableAdGroupCriterion);
        if (cpcBidAmount != null) {
          childNode = childNode.setBid(cpcBidAmount.getMicroAmount());
        }
        childNode =
            childNode.setTrackingUrlTemplate(biddableAdGroupCriterion.getTrackingUrlTemplate());
        childNode = copyCustomParametersToNode(biddableAdGroupCriterion, childNode);
      } else {
        childNode = childNode.asExcludedUnit();
      }
    }
    addChildNodes(childNode, parentIdMap);
  }
}
 
Example 11
Source File: HardAssignmentCreator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
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 12
Source File: ProductPartitionTreeImpl.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new instance of this class by retrieving the product partitions of the
 * specified ad group. All parameters are required.
 */
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
    AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
  // Get the AdGroupCriterionService.
  AdGroupCriterionServiceInterface criterionService =
      services.get(session, AdGroupCriterionServiceInterface.class);

  SelectorBuilder selectorBuilder = new SelectorBuilder()
      .fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
          new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
      .equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
      .equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
      .in(
          AdGroupCriterionField.Status,
          UserStatus.ENABLED.getValue(),
          UserStatus.PAUSED.getValue())
      .limit(PAGE_SIZE);

  AdGroupCriterionPage adGroupCriterionPage;

  // A multimap from each product partition ID to its direct children.
  ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
  int offset = 0;
  do {
    // Get the next page of results.
    adGroupCriterionPage = criterionService.get(selectorBuilder.build());

    if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
      for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
        ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
        parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
      }
      offset += adGroupCriterionPage.getEntries().length;
      selectorBuilder.increaseOffsetBy(PAGE_SIZE);
    }
  } while (offset < adGroupCriterionPage.getTotalNumEntries());

  // Construct the ProductPartitionTree from the parentIdMap.
  if (!parentIdMap.containsKey(null)) {
    Preconditions.checkState(parentIdMap.isEmpty(),
        "No root criterion found in the tree but the tree is not empty");
    return createEmptyAdGroupTree(adGroupId,
        getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
  }

  return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
}