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

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

Introduction

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

Prototype

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

Source Link

Document

Returns a new builder.

Usage

From source file:co.cask.cdap.explore.jdbc.ExploreDriver.java

/**
 * Parse Explore connection url string to retrieve the necessary parameters to connect to CDAP.
 * Package visibility for testing.//from  w ww . j  av  a 2 s.c o m
 */
ConnectionParams parseConnectionUrl(String url) {
    // URI does not accept two semicolons in a URL string, hence the substring
    URI jdbcURI = URI.create(url.substring(ExploreJDBCUtils.URI_JDBC_PREFIX.length()));
    String host = jdbcURI.getHost();
    int port = jdbcURI.getPort();
    ImmutableMultimap.Builder<ConnectionParams.Info, String> builder = ImmutableMultimap.builder();

    // get the query params - javadoc for getQuery says that it decodes the query URL with UTF-8 charset.
    String query = jdbcURI.getQuery();
    if (query != null) {
        for (String entry : Splitter.on("&").split(query)) {
            // Need to do it twice because of error in guava libs Issue: 1577
            int idx = entry.indexOf('=');
            if (idx <= 0) {
                continue;
            }

            ConnectionParams.Info info = ConnectionParams.Info.fromStr(entry.substring(0, idx));
            if (info != null) {
                builder.putAll(info, Splitter.on(',').omitEmptyStrings().split(entry.substring(idx + 1)));
            }
        }
    }
    return new ConnectionParams(host, port, builder.build());
}

From source file:org.apache.aurora.scheduler.stats.SlotSizeCounter.java

private void updateStats(String name, Iterable<MachineResource> slots, ResourceBag slotSize) {

    ImmutableMultimap.Builder<String, ResourceBag> builder = ImmutableMultimap.builder();
    for (MachineResource slot : slots) {
        builder.put(getStatName(name, slot.isDedicated(), slot.isRevocable()), slot.getSize());
    }/*from w  w w  .  j a  v a 2s  .  co m*/

    ImmutableMultimap<String, ResourceBag> sizes = builder.build();

    for (String slotGroup : SLOT_GROUPS) {
        String statName = slotGroup + name;
        cachedCounters.get(statName).set(countSlots(sizes.get(statName), slotSize));
    }
}

From source file:org.jclouds.aws.util.AWSUtils.java

public static <R extends HttpRequest> R indexStringArrayToFormValuesWithPrefix(R request, String prefix,
        Object input) {//from  w  ww  . j a v a  2s .  c  om
    checkArgument(checkNotNull(input, "input") instanceof String[],
            "this binder is only valid for String[] : " + input.getClass());
    String[] values = (String[]) input;
    Builder<String, String> builder = ImmutableMultimap.builder();
    for (int i = 0; i < values.length; i++) {
        builder.put(prefix + "." + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + "s[" + i + "]"));
    }
    ImmutableMultimap<String, String> forms = builder.build();
    return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}

From source file:org.apache.calcite.adapter.java.ReflectiveSchema.java

@Override
protected Multimap<String, Function> getFunctionMultimap() {
    final ImmutableMultimap.Builder<String, Function> builder = ImmutableMultimap.builder();
    for (Method method : clazz.getMethods()) {
        final String methodName = method.getName();
        if (method.getDeclaringClass() == Object.class || methodName.equals("toString")) {
            continue;
        }/*from   w  w w .j a  v  a  2 s .  co  m*/
        if (TranslatableTable.class.isAssignableFrom(method.getReturnType())) {
            final TableMacro tableMacro = new MethodTableMacro(this, method);
            builder.put(methodName, tableMacro);
        }
    }
    return builder.build();
}

From source file:com.publictransitanalytics.scoregenerator.datalayer.directories.GTFSReadingStopTimesDirectory.java

private void parseFrequenciesFile(final ImmutableMultimap.Builder<String, FrequencyRecord> builder,
        final Reader frequenciesReader) throws FileNotFoundException, IOException {

    final CSVParser frequenciesParser = new CSVParser(frequenciesReader, CSVFormat.DEFAULT.withHeader());
    final List<CSVRecord> frequenciesRecords = frequenciesParser.getRecords();

    for (CSVRecord record : frequenciesRecords) {
        final String tripId = record.get("trip_id");

        final FrequencyRecord frequencyRecord = new FrequencyRecord(tripId,
                TransitTime.parse(record.get("start_time")), TransitTime.parse(record.get("end_time")),
                Duration.ofSeconds(Long.parseLong(record.get("headway_secs"))));
        builder.put(tripId, frequencyRecord);
    }// w w  w.  j  a  v a  2 s  .  c o m
}

From source file:ratpack.http.HttpUrlBuilder.java

/**
 * Add some query params to the URL./*  w  w w.  j a  va  2  s .  c  o m*/
 * <p>
 * The given action will be supplied with a multi map builder, to which it can contribute query params.
 * <p>
 * This method is additive with regard to the query params of this builder.
 *
 * @param params an action that contributes query params
 * @return this
 * @throws Exception any thrown by {@code params}
 */
default HttpUrlBuilder params(Action<? super ImmutableMultimap.Builder<String, Object>> params)
        throws Exception {
    return params(Action.with(ImmutableMultimap.builder(), params).build());
}

From source file:co.cask.cdap.data.stream.service.MDSStreamMetaStore.java

@Override
public Multimap<Id.Namespace, StreamSpecification> listStreams() throws Exception {
    return txnl.executeUnchecked(
            new TransactionExecutor.Function<StreamMds, Multimap<Id.Namespace, StreamSpecification>>() {
                @Override/*from  w ww .j  ava  2s  . c o m*/
                public Multimap<Id.Namespace, StreamSpecification> apply(StreamMds mds) throws Exception {
                    ImmutableMultimap.Builder<Id.Namespace, StreamSpecification> builder = ImmutableMultimap
                            .builder();
                    Map<MDSKey, StreamSpecification> streamSpecs = mds.streams
                            .listKV(new MDSKey.Builder().add(TYPE_STREAM).build(), StreamSpecification.class);
                    for (Map.Entry<MDSKey, StreamSpecification> streamSpecEntry : streamSpecs.entrySet()) {
                        MDSKey.Splitter splitter = streamSpecEntry.getKey().split();
                        // skip the first name ("stream")
                        splitter.skipString();
                        // Namespace id is the next part.
                        String namespaceId = splitter.getString();
                        builder.put(Id.Namespace.from(namespaceId), streamSpecEntry.getValue());
                    }
                    return builder.build();
                }
            });
}

From source file:org.streamingpool.ext.tensorics.streamfactory.DetailedTensoricsExpressionStreamFactory.java

private <T, E extends Expression<T>> Flowable<DetailedExpressionResult<T, E>> resolvedStream(
        DetailedExpressionStreamId<T, E> id, DiscoveryService discoveryService) {
    E expression = id.expression();/* www. ja v a  2  s  . c o  m*/
    ResolvingContext initialCtx = id.initialContext();

    Map<Expression<Object>, StreamId<Object>> streamIds = streamIdsFrom(id);
    ImmutableMultimap.Builder<StreamId<?>, Flowable<ExpToValue>> builder = ImmutableMultimap.builder();
    for (Entry<Expression<Object>, StreamId<Object>> entry : streamIds.entrySet()) {
        Flowable<?> plainObservable = fromPublisher(discoveryService.discover(entry.getValue()));
        Flowable<ExpToValue> mappedObservable;
        mappedObservable = plainObservable.map(obj -> new ExpToValue(entry.getKey(), obj));
        builder.put(entry.getValue(), mappedObservable);
    }
    ImmutableMultimap<StreamId<?>, Flowable<ExpToValue>> observableEntries = builder.build();

    EvaluationStrategy evaluationStrategy = initialCtx
            .resolvedValueOf(Placeholder.ofClass(EvaluationStrategy.class));

    Flowable<?> triggerObservable = triggerObservable(observableEntries, evaluationStrategy, discoveryService);
    return triggerObservable
            .withLatestFrom(observableEntries.values().toArray(new Flowable[] {}), CONTEXT_COMBINER)
            .map(ctx -> {
                EditableResolvingContext fullContext = Contexts.newResolvingContext();
                fullContext.putAllNew(ctx);
                fullContext.putAllNew(initialCtx);
                return engine.resolveDetailed(expression, fullContext, EXCEPTION_HANDLING_STRATEGY);
            });
}

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.//  w ww . ja  va 2s. 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();
}

From source file:de.se_rwth.langeditor.modelstates.ModelStateAssembler.java

private ModelState createNewModelState(IStorage storage, IProject project, String content, Language language) {

    ImmutableMultimap.Builder<SourcePosition, String> syntaxErrorBuilder = ImmutableMultimap.builder();

    ParserRuleContext rootContext = language.getParserConfig().parse(content,
            (pos, message) -> syntaxErrorBuilder.put(pos, message));

    nodes.addNodes(rootContext);// ww w.  ja  v a 2s  .  c o m

    return new ModelStateBuilder().setStorage(storage).setProject(project).setContent(content)
            .setLanguage(language).setRootNode(Nodes.getAstNode(rootContext).get()).setRootContext(rootContext)
            .setSyntaxErrors(syntaxErrorBuilder.build())
            .setLastModelState(observableModelStates.findModelState(storage).orElse(null)).build();
}