Example usage for com.google.common.collect Maps asMap

List of usage examples for com.google.common.collect Maps asMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps asMap.

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V> NavigableMap<K, V> asMap(NavigableSet<K> set, Function<? super K, V> function) 

Source Link

Document

Returns a view of the navigable set as a map, mapping keys from the set according to the specified function.

Usage

From source file:dagger.internal.codegen.SimpleMethodBindingExpression.java

@Override
Expression getDependencyExpression(ClassName requestingClass) {
    ImmutableMap<DependencyRequest, Expression> arguments = ImmutableMap.copyOf(Maps
            .asMap(provisionBinding.dependencies(), request -> dependencyArgument(request, requestingClass)));
    Function<DependencyRequest, CodeBlock> argumentsFunction = request -> arguments.get(request).codeBlock();
    return requiresInjectionMethod(provisionBinding, arguments.values().asList(), compilerOptions,
            requestingClass.packageName(), types) ? invokeInjectionMethod(argumentsFunction, requestingClass)
                    : invokeMethod(argumentsFunction, requestingClass);
}

From source file:com.addthis.bundle.core.BundleMapView.java

@Override
public Set<Map.Entry<BundleField, ValueObject>> entrySet() {
    return Maps.asMap(keySet(), bundle::getValue).entrySet();
}

From source file:ninja.leaping.permissionsex.extrabackends.groupmanager.GroupManagerSubjectData.java

@Override
public Map<Set<Map.Entry<String, String>>, Map<String, Integer>> getAllPermissions() {
    return Maps.filterValues(Maps.asMap(getActiveContexts(), this::getPermissions),
            input -> input != null && !input.isEmpty());
}

From source file:com.android.builder.files.IncrementalRelativeFileSets.java

/**
 * Reads a zip file and adds all files in the file in a new incremental relative set. The
 * status of each file is set to {@code status}.
 *
 * @param zip the zip file to read, must be a valid, existing zip file
 * @param status the status to set the files to
 * @return the file set/*w  w w.  j av a  2  s.co m*/
 * @throws IOException failed to read the zip file
 */
@NonNull
public static ImmutableMap<RelativeFile, FileStatus> fromZip(@NonNull File zip, FileStatus status)
        throws IOException {
    Preconditions.checkArgument(zip.isFile(), "!zip.isFile()");

    Set<RelativeFile> files = Sets.newHashSet();

    Closer closer = Closer.create();
    try {
        ZFile zipReader = closer.register(new ZFile(zip));
        for (StoredEntry entry : zipReader.entries()) {
            if (entry.getType() == StoredEntryType.FILE) {
                File file = new File(zip,
                        FileUtils.toSystemDependentPath(entry.getCentralDirectoryHeader().getName()));
                files.add(new RelativeFile(zip, file));
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t, IOException.class);
    } finally {
        closer.close();
    }

    Map<RelativeFile, FileStatus> map = Maps.asMap(files, Functions.constant(status));
    return ImmutableMap.copyOf(map);
}

From source file:com.palantir.atlasdb.cli.command.SweepCommand.java

@Override
public int execute(final AtlasDbServices services) {
    SweepTaskRunner sweepRunner = services.getSweepTaskRunner();

    if (!((namespace != null) ^ (table != null) ^ sweepAllTables)) {
        System.err.println("Specify one of --namespace, --table, or --all options.");
        return 1;
    }//from   ww w.ja  v  a 2 s .c  om
    if ((namespace != null) && (row != null)) {
        System.err.println("Cannot specify a start row (" + row
                + ") when sweeping multiple tables (in namespace " + namespace + ")");
        return 1;
    }

    Map<TableReference, Optional<byte[]>> tableToStartRow = Maps.newHashMap();

    if ((table != null)) {
        Optional<byte[]> startRow = Optional.of(new byte[0]);
        if (row != null) {
            startRow = Optional.of(decodeStartRow(row));
        }
        tableToStartRow.put(TableReference.createUnsafe(table), startRow);
    } else if (namespace != null) {
        Set<TableReference> tablesInNamespace = services.getKeyValueService().getAllTableNames().stream()
                .filter(tableRef -> tableRef.getNamespace().getName().equals(namespace))
                .collect(Collectors.toSet());
        for (TableReference table : tablesInNamespace) {
            tableToStartRow.put(table, Optional.of(new byte[0]));
        }
    } else if (sweepAllTables) {
        tableToStartRow.putAll(Maps.asMap(Sets.difference(services.getKeyValueService().getAllTableNames(),
                AtlasDbConstants.hiddenTables), Functions.constant(Optional.of(new byte[0]))));
    }

    for (Map.Entry<TableReference, Optional<byte[]>> entry : tableToStartRow.entrySet()) {
        final TableReference table = entry.getKey();
        Optional<byte[]> startRow = entry.getValue();

        final AtomicLong cellsExamined = new AtomicLong();
        final AtomicLong cellsDeleted = new AtomicLong();

        while (startRow.isPresent()) {
            Stopwatch watch = Stopwatch.createStarted();
            SweepResults results = sweepRunner.run(table, batchSize, startRow.get());
            System.out.println(String.format(
                    "Swept from %s to %s in table %s in %d ms, examined %d unique cells, deleted %d cells.",
                    encodeStartRow(startRow), encodeEndRow(results.getNextStartRow()), table,
                    watch.elapsed(TimeUnit.MILLISECONDS), results.getCellsExamined(),
                    results.getCellsDeleted()));
            startRow = results.getNextStartRow();
            cellsDeleted.addAndGet(results.getCellsDeleted());
            cellsExamined.addAndGet(results.getCellsExamined());
            maybeSleep();
        }

        services.getTransactionManager().runTaskWithRetry((TxTask) t -> {
            SweepPriorityTable priorityTable = SweepTableFactory.of().getSweepPriorityTable(t);
            SweepPriorityTable.SweepPriorityRow row1 = SweepPriorityTable.SweepPriorityRow
                    .of(table.getQualifiedName());
            priorityTable.putWriteCount(row1, 0L);
            priorityTable.putCellsDeleted(row1, cellsDeleted.get());
            priorityTable.putCellsExamined(row1, cellsExamined.get());
            priorityTable.putLastSweepTime(row1, System.currentTimeMillis());

            System.out
                    .println(String.format("Finished sweeping %s, examined %d unique cells, deleted %d cells.",
                            table, cellsExamined.get(), cellsDeleted.get()));

            if (cellsDeleted.get() > 0) {
                Stopwatch watch = Stopwatch.createStarted();
                services.getKeyValueService().compactInternally(table);
                System.out.println(String.format("Finished performing compactInternally on %s in %d ms.", table,
                        watch.elapsed(TimeUnit.MILLISECONDS)));
            }
            return null;
        });
    }
    return 0;
}

From source file:google.registry.rde.RdeStagingMapper.java

@Override
public final void map(final EppResource resource) {
    // The mapreduce has one special input that provides a null resource. This is used as a sentinel
    // to indicate that we should emit the Registrar objects on this map shard, as these need to be
    // added to every deposit. It is important that these be emitted as part of the mapreduce and
    // not added in a separate stage, because the reducer only runs if there is at least one value
    // emitted from the mapper. Without this, a cursor might never advance because no EppResource
    // entity exists at the watermark.
    if (resource == null) {
        for (Registrar registrar : Registrar.loadAll()) {
            DepositFragment fragment = marshaller.marshalRegistrar(registrar);
            for (PendingDeposit pending : pendings.values()) {
                emit(pending, fragment);
            }// www. j  av a 2s. c om
        }
        return;
    }

    // Skip polymorphic entities that share datastore kind.
    if (!(resource instanceof ContactResource || resource instanceof DomainResource
            || resource instanceof HostResource)) {
        return;
    }

    // Skip prober data.
    if (nullToEmpty(resource.getCreationClientId()).startsWith("prober-")
            || nullToEmpty(resource.getCurrentSponsorClientId()).startsWith("prober-")
            || nullToEmpty(resource.getLastEppUpdateClientId()).startsWith("prober-")) {
        return;
    }

    // Contacts and hosts get emitted on all TLDs, even if domains don't reference them.
    boolean shouldEmitOnAllTlds = !(resource instanceof DomainResource);

    // Get the set of all TLDs to which this resource should be emitted.
    ImmutableSet<String> tlds = shouldEmitOnAllTlds ? pendings.keySet()
            : ImmutableSet.of(((DomainResource) resource).getTld());

    // Get the set of all point-in-time watermarks we need, to minimize rewinding.
    ImmutableSet<DateTime> dates = FluentIterable
            .from(shouldEmitOnAllTlds ? pendings.values() : pendings.get(((DomainResource) resource).getTld()))
            .transform(new Function<PendingDeposit, DateTime>() {
                @Override
                public DateTime apply(PendingDeposit pending) {
                    return pending.watermark();
                }
            }).toSet();

    // Launch asynchronous fetches of point-in-time representations of resource.
    ImmutableMap<DateTime, Result<EppResource>> resourceAtTimes = ImmutableMap
            .copyOf(Maps.asMap(dates, new Function<DateTime, Result<EppResource>>() {
                @Override
                public Result<EppResource> apply(DateTime input) {
                    return EppResourceUtils.loadAtPointInTime(resource, input);
                }
            }));

    // Convert resource to an XML fragment for each watermark/mode pair lazily and cache the result.
    Fragmenter fragmenter = new Fragmenter(resourceAtTimes);

    // Emit resource as an XML fragment for all TLDs and modes pending deposit.
    for (String tld : tlds) {
        for (PendingDeposit pending : pendings.get(tld)) {
            // Hosts and contacts don't get included in BRDA deposits.
            if (pending.mode() == RdeMode.THIN
                    && (resource instanceof ContactResource || resource instanceof HostResource)) {
                continue;
            }
            for (DepositFragment fragment : fragmenter.marshal(pending.watermark(), pending.mode()).asSet()) {
                emit(pending, fragment);
            }
        }
    }

    // Avoid running out of memory.
    ofy().clearSessionCache();
}

From source file:ninja.leaping.permissionsex.extrabackends.groupmanager.GroupManagerSubjectData.java

@Override
public Map<Set<Map.Entry<String, String>>, List<Map.Entry<String, String>>> getAllParents() {
    return Maps.filterValues(Maps.asMap(getActiveContexts(), this::getParents),
            input -> input != null && !input.isEmpty());
}

From source file:com.eucalyptus.component.groups.ServiceGroup.java

public Supplier<Map<ComponentId, Boolean>> groupMemberSupplier() {
    return new Supplier<Map<ComponentId, Boolean>>() {
        @Override//  w  w  w. j  a va  2 s  .c o m
        public Map<ComponentId, Boolean> get() {
            return Maps.asMap(Sets.newHashSet(ComponentIds.list()), Functions.forPredicate(ServiceGroup.this));
        }
    };
}

From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java

public static <K, V> Map<K, V> constantValueMap(Set<K> keys, V v) {
    return Maps.asMap(keys, Functions.constant(v));
}

From source file:com.microsoft.rest.ServiceResponseBuilder.java

@Override
public <THeader> ServiceResponseWithHeaders<T, THeader> buildWithHeaders(final Response<ResponseBody> response,
        Class<THeader> headerType) throws IOException {
    ServiceResponse<T> bodyResponse = build(response);
    THeader headers = serializerAdapter.deserialize(
            serializerAdapter.serialize(Maps.asMap(response.headers().names(), new Function<String, String>() {
                @Override//from ww w.  j  a  v a2 s  . com
                public String apply(String s) {
                    return response.headers().get(s);
                }
            })), headerType);
    return new ServiceResponseWithHeaders<>(bodyResponse.body(), headers, bodyResponse.response());
}