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:org.glassfish.jersey.message.internal.HeadersFactory.java

/**
 * Returns string view of passed headers. Any modifications to the headers are visible to the view, the view also
 * supports removal of elements. Does not support other modifications.
 *
 * @param headers headers./*from ww w .ja v a  2s .com*/
 * @return String view of headers or {@code null} if {code headers} input parameter is {@code null}.
 */
public static MultivaluedMap<String, String> asStringHeaders(final MultivaluedMap<String, Object> headers) {
    if (headers == null) {
        return null;
    }

    final RuntimeDelegate rd = RuntimeDelegate.getInstance();
    return new AbstractMultivaluedMap<String, String>(
            Maps.transformValues(headers, new Function<List<Object>, List<String>>() {
                @Override
                public List<String> apply(List<Object> input) {
                    return HeadersFactory.asStringList(input, rd);
                }
            })) {
    };
}

From source file:org.opendaylight.mdsal.dom.broker.DOMRpcRoutingTable.java

Map<SchemaPath, Set<YangInstanceIdentifier>> getRpcs() {
    return Maps.transformValues(rpcs, EXTRACT_IDENTIFIERS);
}

From source file:ninja.leaping.permissionsex.backend.sql.SqlSubjectData.java

@Override
public Map<Set<Entry<String, String>>, Map<String, Integer>> getAllPermissions() {
    return Maps.filterValues(
            Maps.transformValues(segments, dataEntry -> dataEntry == null ? null : dataEntry.getPermissions()),
            o -> o != null);/*from  www  .ja  v  a 2 s.  c o  m*/
}

From source file:co.cask.cdap.internal.app.runtime.adapter.PluginRepository.java

/**
 * Returns a {@link Map.Entry} represents the plugin information for the plugin being requested.
 *
 * @param template name of the template//from ww  w  .  ja va 2  s .  c  o  m
 * @param pluginType plugin type name
 * @param pluginName plugin name
 * @param selector for selecting which plugin to use
 * @return the entry found or {@code null} if none was found
 */
@Nullable
public Map.Entry<PluginInfo, PluginClass> findPlugin(String template, final String pluginType,
        final String pluginName, PluginSelector selector) {
    // Transform by matching type, name. If there is no match, the map value is null.
    // We then filter out null value
    SortedMap<PluginInfo, PluginClass> plugins = ImmutableSortedMap.copyOf(Maps.filterValues(
            Maps.transformValues(getPlugins(template), new Function<Collection<PluginClass>, PluginClass>() {
                @Nullable
                @Override
                public PluginClass apply(Collection<PluginClass> input) {
                    for (PluginClass pluginClass : input) {
                        if (pluginClass.getType().equals(pluginType)
                                && pluginClass.getName().equals(pluginName)) {
                            return pluginClass;
                        }
                    }
                    return null;
                }
            }), Predicates.notNull()));

    return plugins.isEmpty() ? null : selector.select(plugins);
}

From source file:co.cask.hydrator.plugin.realtime.KafkaSimpleApiConsumer.java

/**
 * Will be called by external source to start poll the Kafka messages one at the time.
 *
 * @param emitter instance of {@link Emitter} to emit the messages.
 *///w  w w.jav a2s.c om
public void pollMessages(Emitter<StructuredRecord> emitter) throws Exception {
    // Configure consumers late to read from SourceState
    if (consumerInfos == null) {
        consumerInfos = createConsumerInfos(kafkaConfigurer.getTopicPartitions());
    }

    boolean infosUpdated = false;
    // Poll for messages from Kafka
    for (KafkaConsumerInfo<OFFSET> info : consumerInfos.values()) {
        Iterator<KafkaMessage<OFFSET>> iterator = readMessages(info);
        while (iterator.hasNext()) {
            KafkaMessage<OFFSET> message = iterator.next();
            processMessage(message, emitter);

            // Update the read offset
            info.setReadOffset(message.getNextOffset());
        }
        if (info.hasPendingChanges()) {
            infosUpdated = true;
        }
    }

    // Save new offset if there is at least one message processed, or even if the offset simply changed.
    if (infosUpdated) {
        saveReadOffsets(Maps.transformValues(consumerInfos, consumerToOffset));
    }
}

From source file:ninja.utils.FakeContext.java

@Override
public Map<String, String[]> getParameters() {
    return Maps.transformValues(params.asMap(), new Function<Collection<String>, String[]>() {
        @Override/*from   ww  w  .  j a  va  2 s  .c  om*/
        public String[] apply(Collection<String> s) {
            return s.toArray(new String[s.size()]);
        }
    });
}

From source file:br.com.tecsinapse.exporter.importer.ImporterUtils.java

public static final Map<Method, TableCellMapping> getMappedMethods(Class<?> clazz, final Class<?> group) {

    Set<Method> cellMappingMethods = ReflectionUtils.getAllMethods(clazz,
            ReflectionUtils.withAnnotation(TableCellMapping.class));
    cellMappingMethods.addAll(/*from  w  w w .j  ava  2 s  .  c  om*/
            ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withAnnotation(TableCellMappings.class)));

    Multimap<Method, Optional<TableCellMapping>> tableCellMappingByMethod = FluentIterable
            .from(cellMappingMethods).index(new Function<Method, Optional<TableCellMapping>>() {
                @Override
                public Optional<TableCellMapping> apply(@Nonnull Method method) {
                    checkNotNull(method);
                    return Optional.fromNullable(method.getAnnotation(TableCellMapping.class))
                            .or(getFirstTableCellMapping(method.getAnnotation(TableCellMappings.class), group));
                }
            }).inverse();

    tableCellMappingByMethod = filterEntries(tableCellMappingByMethod,
            new Predicate<Entry<Method, Optional<TableCellMapping>>>() {
                @Override
                public boolean apply(@Nonnull Entry<Method, Optional<TableCellMapping>> entry) {
                    checkNotNull(entry);
                    return entry.getValue().isPresent()
                            && any(Lists.newArrayList(entry.getValue().get().groups()), assignableTo(group));
                }
            });

    Multimap<Method, TableCellMapping> methodByTableCellMapping = transformValues(tableCellMappingByMethod,
            new Function<Optional<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Optional<TableCellMapping> tcmOptional) {
                    checkNotNull(tcmOptional);
                    return tcmOptional.get();
                }
            });

    return Maps.transformValues(methodByTableCellMapping.asMap(),
            new Function<Collection<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Collection<TableCellMapping> tcms) {
                    checkNotNull(tcms);
                    return Iterables.getFirst(tcms, null);
                }
            });
}

From source file:co.cask.cdap.template.etl.realtime.kafka.KafkaSimpleApiConsumer.java

/**
 * Will be called by external source to start poll the Kafka messages one at the time.
 *
 * @param emitter instance of {@link Emitter} to emit the messages.
 *//* w ww .j  a v a  2s .  c  o  m*/
public void pollMessages(Emitter<StructuredRecord> emitter) {
    // Configure consumers late to read from Adapter SourceState
    if (consumerInfos == null) {
        consumerInfos = createConsumerInfos(kafkaConfigurer.getTopicPartitions());
    }

    boolean infosUpdated = false;
    // Poll for messages from Kafka
    for (KafkaConsumerInfo<OFFSET> info : consumerInfos.values()) {
        Iterator<KafkaMessage<OFFSET>> iterator = readMessages(info);
        while (iterator.hasNext()) {
            KafkaMessage<OFFSET> message = iterator.next();
            processMessage(message, emitter);

            // Update the read offset
            info.setReadOffset(message.getNextOffset());
        }
        if (info.hasPendingChanges()) {
            infosUpdated = true;
        }
    }

    // Save new offset if there is at least one message processed, or even if the offset simply changed.
    if (infosUpdated) {
        saveReadOffsets(Maps.transformValues(consumerInfos, consumerToOffset));
    }
}

From source file:com.isotrol.impe3.core.modules.ModuleDefinition.java

/**
 * If is a connector module, return connector provision. Else, throws an illegalstate exception.
 * @return map of connector provision.//from ww w  . j a v  a2s  . co  m
 */
public final Map<String, ConnectorProvision> getConnectorProvisions() {
    Preconditions.checkState(getModuleType() == ModuleType.CONNECTOR);
    return Maps.transformValues(getProvisions(), TO_CONNECTOR_PROVISION);
}

From source file:com.nesscomputing.httpserver.log.syslog.SyslogRequestLog.java

@Override
public void log(final Request request, final Response response) {
    if (syslog == null) {
        return;// w  ww .ja  v a  2 s.  c  o m
    }

    final String requestUri = request.getRequestURI();

    for (String blackListEntry : blackList) {
        if (StringUtils.startsWith(requestUri, blackListEntry)) {
            return;
        }
    }

    final String messageId = UUID.randomUUID().toString().replace("-", "");

    final Map<String, Builder<String, String>> builderMap = Maps.newHashMap();

    final Builder<String, String> logBuilder = ImmutableMap.builder();
    builderMap.put("l@" + ianaIdentifier, logBuilder);

    if (galaxyConfig != null) {
        if (galaxyConfig.getEnv().getAgentId() != null) {
            logBuilder.put("si", galaxyConfig.getEnv().getAgentId());
        }
        if (galaxyConfig.getDeploy().getConfig() != null) {
            logBuilder.put("sc", galaxyConfig.getDeploy().getConfig());
        }
    }

    for (Iterator<String> it = logFields.iterator(); it.hasNext();) {
        // Parse out fields that have parameters e.g. header:X-Trumpet-Track, and print
        final String[] chunks = StringUtils.split(it.next(), ":");

        final LogField field = knownFields.get(chunks[0]);
        if (chunks.length == 1) {
            final Object result = field.log(request, response, null);
            if (result != null) {
                logBuilder.put(field.getShortName(), result.toString());
            }
        } else if (chunks.length == 2) {
            final String fieldName = field.getShortName() + "@" + ianaIdentifier;
            Builder<String, String> subBuilder = builderMap.get(fieldName);
            if (subBuilder == null) {
                subBuilder = new Builder<String, String>();
                builderMap.put(fieldName, subBuilder);
            }
            final String fieldKey = chunks[1].toLowerCase(Locale.ENGLISH).replace("=", "_");
            final Object result = field.log(request, response, chunks[1]);
            if (result != null) {
                subBuilder.put(fieldKey, result.toString());
            }
        }
    }

    final String threadName = StringUtils.replaceChars(Thread.currentThread().getName(), " \t", "");

    final StructuredSyslogMessage structuredMessage = new StructuredSyslogMessage(messageId, threadName,
            Maps.transformValues(builderMap, new Function<Builder<String, String>, Map<String, String>>() {
                @Override
                public Map<String, String> apply(final Builder<String, String> builder) {
                    return builder.build();
                }
            }), null);
    syslog.info(structuredMessage);
}