Example usage for com.google.common.collect ImmutableMultimap.Builder put

List of usage examples for com.google.common.collect ImmutableMultimap.Builder put

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap.Builder put.

Prototype

@Deprecated
@Override
public boolean put(K key, V value) 

Source Link

Document

Guaranteed to throw an exception and leave the multimap unmodified.

Usage

From source file:org.jclouds.ec2.binders.BindBlockDeviceMappingToIndexedFormParams.java

@SuppressWarnings("unchecked")
@Override/*from w w  w  .  jav  a  2s .c  om*/
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map");
    Map<String, BlockDevice> blockDeviceMapping = (Map<String, BlockDevice>) input;
    Multimap<String, String> original = queryParser().apply(request.getPayload().getRawContent().toString());
    ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
    builder.putAll("Action", "ModifyInstanceAttribute");
    int amazonOneBasedIndex = 1; // according to docs, counters must start with 1
    for (Entry<String, BlockDevice> ebsBlockDeviceName : blockDeviceMapping.entrySet()) {
        // not null by contract
        builder.put(format(deviceNamePattern, amazonOneBasedIndex), ebsBlockDeviceName.getKey());
        builder.put(format(deleteOnTerminationPattern, amazonOneBasedIndex),
                String.valueOf(ebsBlockDeviceName.getValue().isDeleteOnTermination()));
        builder.put(format(volumeIdPattern, amazonOneBasedIndex), ebsBlockDeviceName.getValue().getVolumeId());
        amazonOneBasedIndex++;
    }
    builder.putAll("InstanceId", original.get("InstanceId"));
    request.setPayload(newUrlEncodedFormPayload(builder.build()));
    return request;
}

From source file:org.jclouds.cloudwatch.binders.MetricDataBinder.java

/**
 * {@inheritDoc}/*from www  .  jav a  2s  .  c om*/
 */
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
    Iterable<MetricDatum> metrics = (Iterable<MetricDatum>) checkNotNull(input, "metrics must be set!");

    ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.builder();
    int metricDatumIndex = 1;

    for (MetricDatum metricDatum : metrics) {
        int dimensionIndex = 1;

        for (Dimension dimension : metricDatum.getDimensions()) {
            formParameters.put(
                    "MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + ".Name",
                    dimension.getName());
            formParameters.put(
                    "MetricData.member." + metricDatumIndex + ".Dimensions.member." + dimensionIndex + ".Value",
                    dimension.getValue());
            dimensionIndex++;
        }

        formParameters.put("MetricData.member." + metricDatumIndex + ".MetricName",
                metricDatum.getMetricName());

        if (metricDatum.getStatisticValues().isPresent()) {
            StatisticValues statisticValues = metricDatum.getStatisticValues().get();

            formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Maximum",
                    String.valueOf(statisticValues.getMaximum()));
            formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Minimum",
                    String.valueOf(statisticValues.getMinimum()));
            formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.SampleCount",
                    String.valueOf(statisticValues.getSampleCount()));
            formParameters.put("MetricData.member." + metricDatumIndex + ".StatisticValues.Sum",
                    String.valueOf(statisticValues.getSum()));
        }

        if (metricDatum.getTimestamp().isPresent()) {
            formParameters.put("MetricData.member." + metricDatumIndex + ".Timestamp",
                    dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp().get()));
        }

        formParameters.put("MetricData.member." + metricDatumIndex + ".Unit",
                String.valueOf(metricDatum.getUnit()));

        if (metricDatum.getValue().isPresent()) {
            formParameters.put("MetricData.member." + metricDatumIndex + ".Value",
                    String.valueOf(metricDatum.getValue().get()));
        }

        metricDatumIndex++;
    }

    return (R) request.toBuilder().replaceFormParams(formParameters.build()).build();
}

From source file:com.google.devtools.build.lib.rules.cpp.FdoSupport.java

/**
 * Reads a .afdo.imports file and stores the imports information.
 *///from  w  w  w .  jav a  2  s .co  m
private static ImmutableMultimap<PathFragment, PathFragment> readAutoFdoImports(Path importsFile)
        throws IOException, FdoException {
    ImmutableMultimap.Builder<PathFragment, PathFragment> importBuilder = ImmutableMultimap.builder();
    for (String line : FileSystemUtils.iterateLinesAsLatin1(importsFile)) {
        if (!line.isEmpty()) {
            PathFragment key = new PathFragment(line.substring(0, line.indexOf(':')));
            if (key.isAbsolute()) {
                throw new FdoException(
                        "Absolute paths not allowed in afdo imports file " + importsFile + ": " + key);
            }
            for (String auxFile : line.substring(line.indexOf(':') + 1).split(" ")) {
                if (auxFile.length() == 0) {
                    continue;
                }

                importBuilder.put(key, new PathFragment(auxFile));
            }
        }
    }
    return importBuilder.build();
}

From source file:com.techcavern.pircbotz.UserChannelMap.java

public UserChannelMapSnapshot createSnapshot(Map<U, UserSnapshot> userSnapshots,
        Map<C, ChannelSnapshot> channelSnapshots) {
    //Create new multimaps replacing each user and channel with their respective snapshots
    ImmutableMultimap.Builder<UserSnapshot, ChannelSnapshot> userToChannelSnapshotBuilder = ImmutableMultimap
            .builder();/* w w  w. java  2s  .  c  om*/
    for (Map.Entry<U, C> curEntry : userToChannelMap.entries()) {
        if (userSnapshots.get(curEntry.getKey()) != null && channelSnapshots.get(curEntry.getValue()) != null)
            userToChannelSnapshotBuilder.put(userSnapshots.get(curEntry.getKey()),
                    channelSnapshots.get(curEntry.getValue()));
    }
    ImmutableMultimap.Builder<ChannelSnapshot, UserSnapshot> channelToUserSnapshotBuilder = ImmutableMultimap
            .builder();
    for (Map.Entry<C, U> curEntry : channelToUserMap.entries()) {
        if (channelSnapshots.get(curEntry.getKey()) != null && userSnapshots.get(curEntry.getValue()) != null)
            channelToUserSnapshotBuilder.put(channelSnapshots.get(curEntry.getKey()),
                    userSnapshots.get(curEntry.getValue()));

    } //Return a snapshot of the map
    return new UserChannelMapSnapshot(userToChannelSnapshotBuilder.build(),
            channelToUserSnapshotBuilder.build());
}

From source file:com.isotrol.impe3.core.component.DirectInjectors.java

private DirectInjectors(final Class<T> type, final Predicate<Class<?>> valid, Iterable<Method> methods) {
    super(type);/*from w ww . ja va  2  s. c om*/
    final ImmutableMultimap.Builder<Class<?>, DirectInjector> builder = ImmutableMultimap.builder();
    for (Method m : methods) {
        final DirectInjector i = new DirectInjector(m, valid);
        Class<?> pt = i.getParameterType();
        if (Listing.class.isAssignableFrom(pt)) {
            pt = Listing.class;
        }
        builder.put(pt, i);
    }
    this.injectors = builder.build();
}

From source file:com.imaginarycode.minecraft.hubmagic.HubCommandConfiguration.java

HubCommandConfiguration(Configuration configuration) {
    permissionRequired = configuration.getBoolean("hub-command.requires-permission", false);
    ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
    Configuration configuration1 = configuration.getSection("hub-command.forwarding");

    List<String> global = configuration1.getStringList("global");

    for (String alias : configuration.getStringList("hub-command.aliases")) {
        for (String s : configuration1.getStringList(alias)) {
            builder.put(alias, s);
        }/*from ww  w .j av a  2  s. c o  m*/

        builder.putAll(alias, global);
    }

    skippingPatterns = builder.build();

    Object msgs = configuration.get("hub-command.messages");
    if (msgs != null && msgs instanceof Map) {
        Map<?, ?> msgMap = (Map) msgs;

        for (Map.Entry<?, ?> entry : msgMap.entrySet()) {
            messages.put(entry.getKey().toString(),
                    ChatColor.translateAlternateColorCodes('&', entry.getValue().toString()));
        }
    }
}

From source file:com.facebook.presto.metadata.DatabaseShardManager.java

@Override
public Multimap<Long, Entry<Long, String>> getCommittedPartitionShardNodes(TableHandle tableHandle) {
    checkNotNull(tableHandle, "tableHandle is null");
    checkState(tableHandle instanceof NativeTableHandle, "tableHandle not a native table");
    final long tableId = ((NativeTableHandle) tableHandle).getTableId();

    ImmutableMultimap.Builder<Long, Entry<Long, String>> map = ImmutableMultimap.builder();

    List<ShardNode> shardNodes = dao.getCommittedShardNodesByTableId(tableId);
    for (ShardNode shardNode : shardNodes) {
        map.put(shardNode.getPartitionId(),
                Maps.immutableEntry(shardNode.getShardId(), shardNode.getNodeIdentifier()));
    }//from   ww  w .ja  v a 2s .c o  m
    return map.build();
}

From source file:com.facebook.presto.split.NativeSplitManager.java

@Override
public Iterable<Split> getPartitionSplits(TableHandle tableHandle, List<Partition> partitions) {
    Stopwatch splitTimer = new Stopwatch();
    splitTimer.start();/*from  ww w.  j ava 2s .  c o  m*/

    checkNotNull(partitions, "partitions is null");
    if (partitions.isEmpty()) {
        return ImmutableList.of();
    }

    Map<String, Node> nodesById = uniqueIndex(nodeManager.getAllNodes().getActiveNodes(),
            Node.getIdentifierFunction());

    List<Split> splits = new ArrayList<>();

    Multimap<Long, Entry<Long, String>> partitionShardNodes = shardManager
            .getCommittedPartitionShardNodes(tableHandle);

    for (Partition partition : partitions) {
        checkArgument(partition instanceof NativePartition, "Partition must be a native partition");
        NativePartition nativePartition = (NativePartition) partition;

        ImmutableMultimap.Builder<Long, String> shardNodes = ImmutableMultimap.builder();
        for (Entry<Long, String> partitionShardNode : partitionShardNodes
                .get(nativePartition.getNativePartitionId())) {
            shardNodes.put(partitionShardNode.getKey(), partitionShardNode.getValue());
        }

        for (Map.Entry<Long, Collection<String>> entry : shardNodes.build().asMap().entrySet()) {
            List<HostAddress> addresses = getAddressesForNodes(nodesById, entry.getValue());
            checkState(addresses.size() > 0, "no host for shard %s found", entry.getKey());
            Split split = new NativeSplit(entry.getKey(), addresses);
            splits.add(split);
        }
    }

    log.debug("Split retrieval for %d partitions (%d splits): %dms", partitions.size(), splits.size(),
            splitTimer.elapsed(TimeUnit.MILLISECONDS));

    // the query engine assumes that splits are returned in a somewhat random fashion. The native split manager,
    // because it loads the data from a db table will return the splits somewhat ordered by node id so only a sub
    // set of nodes is fired up. Shuffle the splits to ensure random distribution.
    Collections.shuffle(splits);

    return ImmutableList.copyOf(splits);
}

From source file:org.jclouds.s3.options.CopyObjectOptions.java

@Override
public Multimap<String, String> buildRequestHeaders() {
    checkState(headerTag != null, "headerTag should have been injected!");
    checkState(metadataPrefix != null, "metadataPrefix should have been injected!");
    ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder();
    for (Entry<String, String> entry : headers.entries()) {
        returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue());
    }//from   w w w .ja  v  a2s.com
    if (metadata != null) {
        returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE");
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            String key = entry.getKey();
            returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue());
        }
    }
    return returnVal.build();
}

From source file:google.registry.tools.CreateAuctionCreditsCommand.java

/**
 * Parses the provided CSV file of data from the auction provider and returns a multimap mapping
 * each registrar to the collection of auction credit amounts from this TLD's auctions that should
 * be awarded to this registrar, and validating that every credit amount's currency is in the
 * specified TLD-wide currency.//from ww w.  j  a  v  a  2  s. c om
 */
private static ImmutableMultimap<Registrar, BigMoney> parseCreditsFromCsv(Path csvFile, String tld)
        throws IOException {
    List<String> lines = Files.readAllLines(csvFile, StandardCharsets.UTF_8);
    checkArgument(CsvHeader.getHeaders().equals(splitCsvLine(lines.get(0))),
            "Expected CSV header line not present");
    ImmutableMultimap.Builder<Registrar, BigMoney> builder = new ImmutableMultimap.Builder<>();
    for (String line : Iterables.skip(lines, 1)) {
        List<String> fields = splitCsvLine(line);
        checkArgument(CsvHeader.getHeaders().size() == fields.size(), "Wrong number of fields");
        try {
            String registrarId = fields.get(CsvHeader.AFFILIATE.ordinal());
            Registrar registrar = checkNotNull(Registrar.loadByClientId(registrarId), "Registrar %s not found",
                    registrarId);
            CurrencyUnit tldCurrency = Registry.get(tld).getCurrency();
            CurrencyUnit currency = CurrencyUnit.of((fields.get(CsvHeader.CURRENCY_CODE.ordinal())));
            checkArgument(tldCurrency.equals(currency), "Credit in wrong currency (%s should be %s)", currency,
                    tldCurrency);
            // We use BigDecimal and BigMoney to preserve fractional currency units when computing the
            // total amount of each credit (since auction credits are percentages of winning bids).
            BigDecimal creditAmount = new BigDecimal(fields.get(CsvHeader.COMMISSIONS.ordinal()));
            BigMoney credit = BigMoney.of(currency, creditAmount);
            builder.put(registrar, credit);
        } catch (IllegalArgumentException | IndexOutOfBoundsException e) {
            throw new IllegalArgumentException("Error in line: " + line, e);
        }
    }
    return builder.build();
}