Example usage for com.google.common.collect ImmutableSetMultimap builder

List of usage examples for com.google.common.collect ImmutableSetMultimap builder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSetMultimap builder.

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new Builder .

Usage

From source file:uk.ac.ebi.atlas.experimentimport.analyticsindex.differential.MicroArrayDiffAnalyticsIndexerService.java

ImmutableSetMultimap<String, String> buildConditionSearchTermsByAssayGroupId(DifferentialExperiment experiment,
        SetMultimap<String, String> ontologyTermIdsByAssayAccession) {

    Collection<DifferentialCondition> conditions = diffConditionsBuilder.buildProperties(experiment,
            ontologyTermIdsByAssayAccession);

    ImmutableSetMultimap.Builder<String, String> builder = ImmutableSetMultimap.builder();

    for (DifferentialCondition condition : conditions) {
        builder.putAll(condition.getContrastId(), condition.getValues());
    }/* ww  w .j  a  v  a2  s . c om*/

    return builder.build();

}

From source file:com.google.caliper.core.BenchmarkClassModel.java

/**
 * Returns a multimap containing the full set of parameter values to use for the benchmark. For
 * parameters on the benchmark that have values in the given user-supplied parameters, the user's
 * specified values are used. For all other parameters, the default values specified in the
 * annotation or implied by the type are used.
 *
 * @throws IllegalArgumentException if a parameter for the benchmark has neither user-specified
 *     values nor default values//from  www.  ja  v a 2s  .c  o  m
 */
public final ImmutableSetMultimap<String, String> fillInDefaultParameterValues(
        ImmutableSetMultimap<String, String> userParameters) {
    ImmutableSetMultimap.Builder<String, String> combined = ImmutableSetMultimap.builder();

    // For user parameters, this'll actually be the same as parameters().keySet(), since any extras
    // given at the command line are treated as errors; for VM parameters this is not the case.
    for (String name : Sets.union(parameters().keySet(), userParameters.keySet())) {
        ImmutableSet<String> values = userParameters.containsKey(name) ? userParameters.get(name)
                : parameters().get(name);
        combined.putAll(name, values);
        checkArgument(!values.isEmpty(), "ERROR: No default value provided for %s", name);
    }
    return combined.orderKeysBy(Ordering.natural()).build();
}

From source file:org.sonar.server.computation.measure.MapBasedRawMeasureRepository.java

@Override
public SetMultimap<String, Measure> getRawMeasures(Component component) {
    T componentKey = componentToKey.apply(component);
    Map<MeasureKey, Measure> rawMeasures = measures.get(componentKey);
    if (rawMeasures == null) {
        return ImmutableSetMultimap.of();
    }//w ww.ja v  a2 s . c om

    ImmutableSetMultimap.Builder<String, Measure> builder = ImmutableSetMultimap.builder();
    for (Map.Entry<MeasureKey, Measure> entry : rawMeasures.entrySet()) {
        builder.put(entry.getKey().getMetricKey(), entry.getValue());
    }
    return builder.build();
}

From source file:com.facebook.presto.execution.scheduler.NodeScheduler.java

public NodeSelector createNodeSelector(ConnectorId connectorId) {
    // this supplier is thread-safe. TODO: this logic should probably move to the scheduler since the choice of which node to run in should be
    // done as close to when the the split is about to be scheduled
    Supplier<NodeMap> nodeMap = Suppliers.memoizeWithExpiration(() -> {
        ImmutableSetMultimap.Builder<HostAddress, Node> byHostAndPort = ImmutableSetMultimap.builder();
        ImmutableSetMultimap.Builder<InetAddress, Node> byHost = ImmutableSetMultimap.builder();
        ImmutableSetMultimap.Builder<NetworkLocation, Node> workersByNetworkPath = ImmutableSetMultimap
                .builder();//  w  w w. j ava2s. c o  m

        Set<Node> nodes;
        if (connectorId != null) {
            nodes = nodeManager.getActiveConnectorNodes(connectorId);
        } else {
            nodes = nodeManager.getNodes(ACTIVE);
        }

        Set<String> coordinatorNodeIds = nodeManager.getCoordinators().stream().map(Node::getNodeIdentifier)
                .collect(toImmutableSet());

        for (Node node : nodes) {
            if (useNetworkTopology
                    && (includeCoordinator || !coordinatorNodeIds.contains(node.getNodeIdentifier()))) {
                NetworkLocation location = networkLocationCache.get(node.getHostAndPort());
                for (int i = 0; i <= location.getSegments().size(); i++) {
                    workersByNetworkPath.put(location.subLocation(0, i), node);
                }
            }
            try {
                byHostAndPort.put(node.getHostAndPort(), node);

                InetAddress host = InetAddress.getByName(node.getHttpUri().getHost());
                byHost.put(host, node);
            } catch (UnknownHostException e) {
                // ignore
            }
        }

        return new NodeMap(byHostAndPort.build(), byHost.build(), workersByNetworkPath.build(),
                coordinatorNodeIds);
    }, 5, TimeUnit.SECONDS);

    if (useNetworkTopology) {
        return new TopologyAwareNodeSelector(nodeManager, nodeTaskMap, includeCoordinator, nodeMap,
                minCandidates, maxSplitsPerNode, maxPendingSplitsPerTask, topologicalSplitCounters,
                networkLocationSegmentNames, networkLocationCache);
    } else {
        return new SimpleNodeSelector(nodeManager, nodeTaskMap, includeCoordinator, nodeMap, minCandidates,
                maxSplitsPerNode, maxPendingSplitsPerTask);
    }
}

From source file:org.killbill.billing.plugin.simpletax.internal.TaxCodeService.java

/**
 * Find tax codes that apply to the items of a given invoice, looking for
 * custom fields named {@value #TAX_CODES_FIELD_NAME} that can be attached
 * to these items./*from  www.  j  a  v a 2 s . c o  m*/
 *
 * @param invoice
 *            An invoice in which existing tax codes are to be found.
 * @return The existing tax codes, grouped by the identifiers of their
 *         related invoice items. Never {@code null}, and guaranteed not
 *         having any {@code null} values.
 * @throws NullPointerException
 *             when {@code invoice} is {@code null}.
 */
@Nonnull
public SetMultimap<UUID, TaxCode> findExistingTaxCodes(Invoice invoice) {
    Set<CustomField> taxFields = taxFieldsOfInvoices.get(invoice.getId());
    // Note: taxFields is not null, by Multimap contract

    ImmutableSetMultimap.Builder<UUID, TaxCode> taxCodesOfInvoiceItems = ImmutableSetMultimap.builder();
    for (CustomField taxField : taxFields) {
        if (!TAX_CODES_FIELD_NAME.equals(taxField.getFieldName())) {
            continue;
        }
        String taxCodesCSV = taxField.getFieldValue();
        if (taxCodesCSV == null) {
            continue;
        }
        UUID invoiceItemId = taxField.getObjectId();
        Set<TaxCode> taxCodes = cfg.findTaxCodes(taxCodesCSV,
                "from custom field '" + TAX_CODES_FIELD_NAME + "' of invoice item [" + invoiceItemId + "]");
        taxCodesOfInvoiceItems.putAll(invoiceItemId, taxCodes);
    }
    return taxCodesOfInvoiceItems.build();
}

From source file:com.facebook.buck.java.JavaSymbolFinder.java

/**
 * Figure out the build targets that provide a set of Java symbols.
 * @param symbols The set of symbols (e.g. "com.example.foo.Bar") to find defining targets for.
 *                This is taken as a collection, rather than as an individual string, because
 *                instantiating a ProjectBuildFileParser is expensive (it spawns a Python
 *                subprocess), and we don't want to encourage the caller to do it more than once.
 * @return A multimap of symbols to the targets that define them, of the form:
 *         {"com.example.a.A": set("//com/example/a:a", "//com/another/a:a")}
 *//* w  ww .j  a  va2 s.  c om*/
public ImmutableSetMultimap<String, BuildTarget> findTargetsForSymbols(Set<String> symbols)
        throws InterruptedException {
    // TODO(jacko): Handle files that aren't included in any rule.

    // First find all the source roots in the current project.
    Collection<Path> srcRoots;
    try {
        srcRoots = srcRootsFinder.getAllSrcRootPaths(config.getSrcRoots());
    } catch (IOException e) {
        buckEventBus.post(ThrowableConsoleEvent.create(e, "Error while searching for source roots."));
        return ImmutableSetMultimap.of();
    }

    // Now collect all the code files that define our symbols.
    Multimap<String, Path> symbolsToSourceFiles = HashMultimap.create();
    for (String symbol : symbols) {
        symbolsToSourceFiles.putAll(symbol, getDefiningPaths(symbol, srcRoots));
    }

    // Now find all the targets that define all those code files. We do this in one pass because we
    // don't want to instantiate a new parser subprocess for every symbol.
    Set<Path> allSourceFilePaths = ImmutableSet.copyOf(symbolsToSourceFiles.values());
    Multimap<Path, BuildTarget> sourceFilesToTargets = getTargetsForSourceFiles(allSourceFilePaths);

    // Now build the map from from symbols to build targets.
    ImmutableSetMultimap.Builder<String, BuildTarget> symbolsToTargets = ImmutableSetMultimap.builder();
    for (String symbol : symbolsToSourceFiles.keySet()) {
        for (Path sourceFile : symbolsToSourceFiles.get(symbol)) {
            symbolsToTargets.putAll(symbol, sourceFilesToTargets.get(sourceFile));
        }
    }

    return symbolsToTargets.build();
}

From source file:co.cask.cdap.internal.app.runtime.flow.FlowUtils.java

/**
 * Configures all queues being used in a flow.
 *
 * @return A Multimap from flowletId to QueueName where the flowlet is a consumer of.
 */// w w  w .j a v  a  2 s.  c om
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec,
        StreamAdmin streamAdmin, QueueAdmin queueAdmin, TransactionExecutorFactory txExecutorFactory) {
    // Generate all queues specifications
    Id.Application appId = Id.Application.from(program.getNamespaceId(), program.getApplicationId());
    Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator(
            appId).create(flowSpec);

    // For each queue in the flow, gather all consumer groups information
    Multimap<QueueName, ConsumerGroupConfig> queueConfigs = HashMultimap.create();

    // Loop through each flowlet and generate the map from consumer flowlet id to queue
    ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder();
    for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) {
        String flowletId = entry.getKey();

        for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) {
            resultBuilder.put(flowletId, queueSpec.getQueueName());
        }
    }

    // For each queue, gather all consumer groups.
    for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.values())) {
        QueueName queueName = queueSpec.getQueueName();
        queueConfigs.putAll(queueName, getAllConsumerGroups(program, flowSpec, queueName, queueSpecs));
    }

    try {
        // Configure each stream consumer in the Flow. Also collects all queue configurers.
        final List<ConsumerGroupConfigurer> groupConfigurers = Lists.newArrayList();

        for (Map.Entry<QueueName, Collection<ConsumerGroupConfig>> entry : queueConfigs.asMap().entrySet()) {
            LOG.info("Queue config for {} : {}", entry.getKey(), entry.getValue());
            if (entry.getKey().isStream()) {
                Map<Long, Integer> configs = Maps.newHashMap();
                for (ConsumerGroupConfig config : entry.getValue()) {
                    configs.put(config.getGroupId(), config.getGroupSize());
                }
                streamAdmin.configureGroups(entry.getKey().toStreamId(), configs);
            } else {
                groupConfigurers.add(new ConsumerGroupConfigurer(queueAdmin.getQueueConfigurer(entry.getKey()),
                        entry.getValue()));
            }
        }

        // Configure queue transactionally
        try {
            Transactions.createTransactionExecutor(txExecutorFactory, groupConfigurers)
                    .execute(new TransactionExecutor.Subroutine() {
                        @Override
                        public void apply() throws Exception {
                            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                                configurer.configure();
                            }
                        }
                    });
        } finally {
            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                Closeables.closeQuietly(configurer);
            }
        }

        return resultBuilder.build();
    } catch (Exception e) {
        LOG.error("Failed to configure queues", e);
        throw Throwables.propagate(e);
    }
}

From source file:com.vmware.photon.controller.rootscheduler.service.InMemoryConstraintChecker.java

@Inject
public InMemoryConstraintChecker(XenonRestClient client) {
    Map<String, HostService.State> hosts = new HashMap<>();
    Map<String, DatastoreService.State> datastores = new HashMap<>();

    try {//from  w ww.  j  a v a  2 s  .  co  m
        // Fetch all the hosts from cloudstore
        QueryTask.Query kindClause = new QueryTask.Query().setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
                .setTermMatchValue(Utils.buildKind(HostService.State.class));
        QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification();
        querySpecification.query = kindClause;
        querySpecification.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.EXPAND_CONTENT);
        Operation completedOp = client.query(querySpecification, true);
        ServiceDocumentQueryResult queryResult = completedOp.getBody(QueryTask.class).results;
        for (Map.Entry<String, Object> result : queryResult.documents.entrySet()) {
            HostService.State hostState = Utils.fromJson(result.getValue(), HostService.State.class);
            final int trimLength = (HostServiceFactory.SELF_LINK + "/").length();
            String hostId = hostState.documentSelfLink.substring(trimLength);
            hosts.put(hostId, hostState);
        }

        // Fetch all the datastores from cloudstore
        kindClause = new QueryTask.Query().setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
                .setTermMatchValue(Utils.buildKind(DatastoreService.State.class));
        querySpecification = new QueryTask.QuerySpecification();
        querySpecification.query = kindClause;
        querySpecification.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.EXPAND_CONTENT);
        completedOp = client.query(querySpecification, true);
        queryResult = completedOp.getBody(QueryTask.class).results;
        for (Map.Entry<String, Object> result : queryResult.documents.entrySet()) {
            DatastoreService.State datastoreState = Utils.fromJson(result.getValue(),
                    DatastoreService.State.class);
            final int trimLength = (DatastoreServiceFactory.SELF_LINK + "/").length();
            String datastoreId = datastoreState.documentSelfLink.substring(trimLength);
            datastores.put(datastoreId, datastoreState);
        }
    } catch (Throwable ex) {
        logger.warn("Failed to fetch host/datastore documents from cloudstore", ex);
    }

    ImmutableMap.Builder<String, ServerAddress> hostBuilder = new ImmutableMap.Builder<>();
    ImmutableSet.Builder<String> managementHostBuilder = new ImmutableSet.Builder<>();
    ImmutableSetMultimap.Builder<String, String> datastoreBuilder = new ImmutableSetMultimap.Builder<>();
    ImmutableSetMultimap.Builder<String, String> datastoreTagBuilder = new ImmutableSetMultimap.Builder<>();
    ImmutableSetMultimap.Builder<String, String> networkBuilder = new ImmutableSetMultimap.Builder<>();
    ImmutableSetMultimap.Builder<String, String> availabilityZoneBuilder = new ImmutableSetMultimap.Builder<>();

    for (Map.Entry<String, HostService.State> host : hosts.entrySet()) {
        if (host.getValue().reportedDatastores == null) {
            logger.warn("Ignoring {}. The reportedDatastores field is null.", host);
            continue;
        }
        if (host.getValue().reportedNetworks == null) {
            logger.warn("Ignoring {}. The reportedNetworks field is null.", host);
            continue;
        }
        if (host.getValue().usageTags == null) {
            logger.warn("Ignoring {}. The usageTags field is null.", host);
            continue;
        }

        hostBuilder.put(host.getKey(),
                new ServerAddress(host.getValue().hostAddress, host.getValue().agentPort));
        if (host.getValue().usageTags.contains(UsageTag.MGMT.name())) {
            managementHostBuilder.add(host.getKey());
        }
        for (String datastoreId : host.getValue().reportedDatastores) {
            datastoreBuilder.put(datastoreId, host.getKey());
            DatastoreService.State datastore = datastores.get(datastoreId);
            if (datastore != null && datastore.tags != null) {
                for (String datastoreTag : datastore.tags) {
                    datastoreTagBuilder.put(datastoreTag, host.getKey());
                }
            }
        }
        for (String networkId : host.getValue().reportedNetworks) {
            networkBuilder.put(networkId, host.getKey());
        }

        if (host.getValue().availabilityZoneId == null) {
            logger.info("{} doesn't have the availabilityZone field set.", host);
        } else {
            availabilityZoneBuilder.put(host.getValue().availabilityZoneId, host.getKey());
        }
    }
    this.hosts = hostBuilder.build();
    this.managementHosts = managementHostBuilder.build();
    this.datastores = datastoreBuilder.build();
    this.datastoreTags = datastoreTagBuilder.build();
    this.networks = networkBuilder.build();
    this.availabilityZones = availabilityZoneBuilder.build();
}

From source file:org.spongepowered.mod.service.world.SpongeChunkLoadService.java

@Override
public ImmutableSetMultimap<Vector3i, LoadingTicket> getForcedChunks(World world) {
    ImmutableSetMultimap<ChunkCoordIntPair, Ticket> forgeForcedChunks = ForgeChunkManager
            .getPersistentChunksFor((net.minecraft.world.World) world);
    ImmutableSetMultimap.Builder<Vector3i, LoadingTicket> spongeForcedChunks = ImmutableSetMultimap.builder();
    for (Map.Entry<ChunkCoordIntPair, Ticket> ticketPair : forgeForcedChunks.entries()) {
        spongeForcedChunks.put(new Vector3i(ticketPair.getKey().chunkXPos, 0, ticketPair.getKey().chunkZPos),
                new SpongeLoadingTicket(ticketPair.getValue()));
    }//from w ww .  j  a v a2  s.co m

    return spongeForcedChunks.build();
}

From source file:org.kiji.schema.zookeeper.UsersTracker.java

/**
 * Retrieve a multimap of the current users to their respective value (either table layout version
 * if tracking table users, or system version if tracking instance users).
 *
 * @return a multimap of the current table users to their respective value.
 * @throws IOException on failure.//from  w  ww .j  a  va 2  s .  co m
 */
public Multimap<String, String> getUsers() throws IOException {
    ImmutableMultimap.Builder<String, String> users = ImmutableSetMultimap.builder();
    for (ChildData child : mCache.getCurrentData()) {
        String nodeName = Iterables.getLast(Splitter.on('/').split(child.getPath()));
        String[] split = nodeName.split(ZooKeeperUtils.ZK_NODE_NAME_SEPARATOR);
        if (split.length != 2) {
            LOG.error("Ignoring invalid ZooKeeper table user node: {}.", nodeName);
            continue;
        }
        final String userID = URLDecoder.decode(split[0], Charsets.UTF_8.displayName());
        final String layoutID = URLDecoder.decode(split[1], Charsets.UTF_8.displayName());

        users.put(userID, layoutID);
    }
    return users.build();
}