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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:com.twitter.aurora.scheduler.storage.log.LogStorage.java

@Timed("scheduler_log_tasks_mutate")
@Override/* w  w w.  j  a  v  a2  s. c o  m*/
public ImmutableSet<IScheduledTask> mutateTasks(final Query.Builder query,
        final Function<IScheduledTask, IScheduledTask> mutator) {

    return write(new MutateWork.Quiet<ImmutableSet<IScheduledTask>>() {
        @Override
        public ImmutableSet<IScheduledTask> apply(MutableStoreProvider unused) {
            ImmutableSet<IScheduledTask> mutated = LogStorage.super.mutateTasks(query, mutator);

            Map<String, IScheduledTask> tasksById = Tasks.mapById(mutated);
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Storing updated tasks to log: " + Maps.transformValues(tasksById, Tasks.GET_STATUS));
            }

            // TODO(William Farner): Avoid writing an op when mutated is empty.
            log(Op.saveTasks(new SaveTasks(IScheduledTask.toBuildersSet(mutated))));
            return mutated;
        }
    });
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private AntiEntropyAdvertisement createAdvertisement() {
    return new AntiEntropyAdvertisement(localMemberId,
            ImmutableMap.copyOf(Maps.transformValues(items, MapValue::digest)));
}

From source file:org.onosproject.store.primitives.impl.EventuallyConsistentMapImpl.java

private AntiEntropyAdvertisement<K> createAdvertisement() {
    return new AntiEntropyAdvertisement<>(localNodeId,
            ImmutableMap.copyOf(Maps.transformValues(items, MapValue::digest)));
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves an immutable map {@link Map} whose entries come from the provided
 * map where the entries' value is an instance of the provided {@link Class}.
 * //  w w w  . j  av a2  s. co m
 * @param m
 *          The map whose entries will be used to construct a filtered map
 *          according to the provided class.
 * @param clazz
 *          The class for filtering the provided map.
 * @return an immutable {@link Map}.
 */
public <V, T> Map<String, T> filter(final Map<String, V> m, final Class<T> clazz) {
    return Maps.transformValues(Maps.filterValues(m, new Predicate<V>() {
        @Override
        public boolean apply(@Nullable final V input) {
            if (input != null) {
                return clazz.isAssignableFrom(input.getClass());
            } else {
                return false;
            }
        }
    }), new Function<V, T>() {
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public T apply(@Nullable final V input) {
            return (T) input;
        }
    });
}

From source file:org.apache.druid.segment.realtime.appenderator.BaseAppenderatorDriver.java

WrappedCommitter wrapCommitter(final Committer committer) {
    final AppenderatorDriverMetadata wrappedMetadata;
    final Map<String, SegmentsForSequence> snapshot;
    synchronized (segments) {
        snapshot = ImmutableMap.copyOf(segments);
    }/*from w w w . j  a  v  a  2s.  c  om*/

    wrappedMetadata = new AppenderatorDriverMetadata(
            ImmutableMap.copyOf(Maps.transformValues(snapshot,
                    (Function<SegmentsForSequence, List<SegmentWithState>>) input -> ImmutableList
                            .copyOf(input.intervalToSegmentStates.values().stream()
                                    .flatMap(segmentsOfInterval -> segmentsOfInterval.getAllSegments().stream())
                                    .collect(Collectors.toList())))),
            snapshot.entrySet().stream().collect(
                    Collectors.toMap(Entry::getKey, e -> e.getValue().lastSegmentId)),
            committer.getMetadata());

    return new WrappedCommitter(committer, wrappedMetadata);
}

From source file:io.druid.segment.realtime.appenderator.AppenderatorDriver.java

private WrappedCommitter wrapCommitter(final Committer committer) {
    final AppenderatorDriverMetadata wrappedMetadata;
    synchronized (activeSegments) {
        wrappedMetadata = new AppenderatorDriverMetadata(ImmutableMap.copyOf(Maps.transformValues(
                activeSegments, new Function<NavigableMap<Long, SegmentIdentifier>, List<SegmentIdentifier>>() {
                    @Override//from   w w w.j  a v a2 s.  c om
                    public List<SegmentIdentifier> apply(NavigableMap<Long, SegmentIdentifier> input) {
                        return ImmutableList.copyOf(input.values());
                    }
                })), ImmutableMap.copyOf(publishPendingSegments), ImmutableMap.copyOf(lastSegmentIds),
                committer.getMetadata());
    }

    return new WrappedCommitter() {
        @Override
        public Object getMetadata() {
            return wrappedMetadata;
        }

        @Override
        public void run() {
            committer.run();
        }
    };
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves an immutable map {@link Map} whose entries come from the provided
 * map where the entries' value's second element is an instance of the
 * provided {@link Class}./*from w w  w  . j a va2 s.  c  o  m*/
 * 
 * @param m
 *          The map whose entries will be used to construct a filtered map
 *          according to the provided class.
 * @param clazz
 *          The class for filtering the provided map.
 * @return an immutable {@link Map}.
 */
public <V, T> Map<String, Pair<Feature, T>> filterp(final Map<String, Pair<Feature, V>> m,
        final Class<T> clazz) {
    return Maps.transformValues(Maps.filterValues(m, new Predicate<Pair<Feature, V>>() {
        @Override
        public boolean apply(@Nullable final Pair<Feature, V> input) {
            if (input != null) {
                return clazz.isAssignableFrom(input.getRight().getClass());
            } else {
                return false;
            }
        }
    }), new Function<Pair<Feature, V>, Pair<Feature, T>>() {
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public Pair<Feature, T> apply(@Nullable final Pair<Feature, V> input) {
            return ImmutablePair.of(input.getLeft(), (T) input.getRight());
        }
    });
}

From source file:com.linecorp.armeria.common.MediaType.java

private Map<String, ImmutableMultiset<String>> parametersAsMap() {
    return Maps.transformValues(parameters.asMap(), ImmutableMultiset::copyOf);
}

From source file:diskCacheV111.srm.dcache.Storage.java

private static <K, V, C extends Iterable<V>> Map<K, Iterable<V>> filterValues(Map<K, C> unfiltered,
        Predicate<V> predicate) {
    return Maps.filterValues(Maps.transformValues(unfiltered, values -> filter(values, predicate)),
            values -> !isEmpty(values));
}

From source file:clocker.mesos.entity.task.marathon.MarathonTaskImpl.java

private Map<String, Object> getMarathonFlags(Entity entity) {
    MutableMap.Builder<String, Object> builder = MutableMap.builder();
    ConfigBag provisioningProperties = ConfigBag
            .newInstance(entity.config().get(SoftwareProcess.PROVISIONING_PROPERTIES));

    // CPU//  ww  w.ja  v  a 2  s. co  m
    Double cpus = entity.config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null)
        cpus = config().get(MarathonTask.CPU_RESOURCES);
    if (cpus == null) {
        Integer minCores = entity.config().get(JcloudsLocationConfig.MIN_CORES);
        if (minCores == null) {
            minCores = provisioningProperties.get(JcloudsLocationConfig.MIN_CORES);
        }
        if (minCores == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minCores = 0;
                for (Processor cpu : template.build().getHardware().getProcessors()) {
                    minCores = minCores + (int) cpu.getCores();
                }
            }
        }
        if (minCores != null) {
            cpus = 1.0d * minCores;
        }
    }
    if (cpus == null)
        cpus = 0.25d;
    builder.put("cpus", cpus);

    // Memory
    Integer memory = entity.config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null)
        memory = config().get(MarathonTask.MEMORY_RESOURCES);
    if (memory == null) {
        Integer minRam = parseMbSizeString(entity.config().get(JcloudsLocationConfig.MIN_RAM));
        if (minRam == null) {
            minRam = parseMbSizeString(provisioningProperties.get(JcloudsLocationConfig.MIN_RAM));
        }
        if (minRam == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                minRam = template.build().getHardware().getRam();
            }
        }
        if (minRam != null) {
            memory = minRam;
        }
    }
    if (memory == null)
        memory = 256;
    builder.put("memory", memory);

    // Inbound ports
    Set<Integer> entityOpenPorts = MutableSet.copyOf(DockerUtils.getContainerPorts(entity));
    entityOpenPorts.addAll(DockerUtils.getOpenPorts(entity));
    if (!config().get(DockerContainer.DOCKER_USE_SSH)) {
        entityOpenPorts.remove(22);
    }
    builder.put("openPorts", Ints.toArray(entityOpenPorts));
    sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts));

    // Direct port mappings
    // Note that the Marathon map is reversed, from container to host, with 0 indicating any host port
    Map<Integer, Integer> bindings = MutableMap.of();
    Map<Integer, Integer> marathonBindings = MutableMap.of();
    for (Integer port : entityOpenPorts) {
        marathonBindings.put(port, 0);
    }
    Map<Integer, Integer> entityBindings = entity.config().get(DockerAttributes.DOCKER_PORT_BINDINGS);
    if (entityBindings != null) {
        for (Integer host : entityBindings.keySet()) {
            bindings.put(entityBindings.get(host), host);
            marathonBindings.put(host, entityBindings.get(host));
        }
    }
    if (bindings.isEmpty()) {
        List<PortAttributeSensorAndConfigKey> entityPortConfig = entity.config()
                .get(DockerAttributes.DOCKER_DIRECT_PORT_CONFIG);
        if (entityPortConfig != null) {
            for (PortAttributeSensorAndConfigKey key : entityPortConfig) {
                PortRange range = entity.config().get(key);
                if (range != null && !range.isEmpty()) {
                    Integer port = range.iterator().next();
                    if (port != null) {
                        bindings.put(port, port);
                        marathonBindings.put(port, port);
                    }
                }
            }
        }
        List<Integer> entityPorts = entity.config().get(DockerAttributes.DOCKER_DIRECT_PORTS);
        if (entityPorts != null) {
            for (Integer port : entityPorts) {
                bindings.put(port, port);
                marathonBindings.put(port, port);
            }
        }
    }
    sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_PORT_BINDINGS, bindings);
    builder.put("portBindings", Lists.newArrayList(marathonBindings.entrySet()));

    // Environment variables and Docker links
    Map<String, Object> environment = MutableMap.copyOf(config().get(DOCKER_CONTAINER_ENVIRONMENT));
    environment.putAll(MutableMap.copyOf(entity.config().get(DOCKER_CONTAINER_ENVIRONMENT)));
    Map<String, Entity> links = entity.config().get(DockerAttributes.DOCKER_LINKS);
    if (links != null && links.size() > 0) {
        LOG.debug("Found links: {}", links);
        Map<String, String> extraHosts = MutableMap.of();
        for (Map.Entry<String, Entity> linked : links.entrySet()) {
            Map<String, Object> linkVars = DockerUtils.generateLinks(getRunningEntity(), linked.getValue(),
                    linked.getKey());
            environment.putAll(linkVars);
            String targetAddress = DockerUtils.getTargetAddress(getRunningEntity(), linked.getValue());
            extraHosts.put(linked.getKey(), targetAddress);
        }
        builder.put("extraHosts", Lists.newArrayList(extraHosts.entrySet()));
    }
    sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    entity.sensors().set(DockerContainer.DOCKER_CONTAINER_ENVIRONMENT, ImmutableMap.copyOf(environment));
    builder.put("environment",
            Lists.newArrayList(Maps.transformValues(environment, Functions.toStringFunction()).entrySet()));

    // Volumes
    Map<String, String> volumes = MutableMap.of();
    Map<String, String> mapping = entity.config().get(DockerHost.DOCKER_HOST_VOLUME_MAPPING);
    if (mapping != null) {
        for (String source : mapping.keySet()) {
            volumes.put(source, mapping.get(source));
        }
    }
    sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    entity.sensors().set(DockerAttributes.DOCKER_VOLUME_MAPPING, volumes);
    builder.put("volumes", Lists.newArrayList(volumes.entrySet()));

    // URIs to copy
    List<String> uris = MutableList.copyOf(config().get(TASK_URI_LIST));
    uris.addAll(MutableList.copyOf(entity.config().get(TASK_URI_LIST)));
    sensors().set(TASK_URI_LIST, uris);
    entity.sensors().set(TASK_URI_LIST, uris);
    builder.put("uris", uris);

    // Docker config
    Optional<String> imageName = Optional.fromNullable(config().get(DOCKER_IMAGE_NAME));
    if (imageName.isPresent()) {
        // Docker image
        builder.put("imageName", imageName.get());
        builder.put("imageVersion", config().get(DOCKER_IMAGE_TAG));

        // Docker command or args
        String command = config().get(COMMAND);
        builder.putIfNotNull("command", command);
        List<String> args = MutableList.copyOf(config().get(ARGS));
        builder.putIfNotNull("args", args);
    } else {
        // OS name for image
        OsFamily os = entity.config().get(JcloudsLocationConfig.OS_FAMILY);
        if (os == null) {
            os = provisioningProperties.get(JcloudsLocationConfig.OS_FAMILY);
        }
        if (os == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                os = template.build().getImage().getOperatingSystem().getFamily();
            }
        }
        if (os == null) {
            os = OsFamily.UBUNTU;
        }
        imageName = Optional.of(Strings.toLowerCase(os.value()));
        builder.put("imageName", "clockercentral/" + imageName.get());

        // OS version specified in regex config
        String version = entity.config().get(JcloudsLocationConfig.OS_VERSION_REGEX);
        if (version == null) {
            version = provisioningProperties.get(JcloudsLocationConfig.OS_VERSION_REGEX);
        }
        if (version == null) {
            TemplateBuilder template = provisioningProperties.get(JcloudsLocationConfig.TEMPLATE_BUILDER);
            if (template != null) {
                version = template.build().getImage().getOperatingSystem().getVersion();
            }
        }
        if (version == null) {
            version = "latest";
        }
        builder.put("imageVersion", version);

        // Empty args
        builder.put("args", ImmutableList.of());

        // Update volume to copy root's authorized keys from the host
        volumes.put("/root/.ssh/authorized_keys", "/root/.ssh/authorized_keys");
        builder.put("volumes", Lists.newArrayList(volumes.entrySet()));
    }

    return builder.build();
}