Example usage for com.google.common.collect ImmutableMap get

List of usage examples for com.google.common.collect ImmutableMap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.ambraproject.rhino.config.PersistenceAdapter.java

public static <E extends Enum<E>> PersistenceAdapter<E, String> byEnumName(Class<E> enumType) {
    ImmutableMap<String, E> enumsByName = Maps.uniqueIndex(Arrays.asList(enumType.getEnumConstants()), E::name);
    return new PersistenceAdapter<E, String>() {
        @Override/*from w ww . j a  v  a 2  s.c o m*/
        public Class<E> getModelClass() {
            return enumType;
        }

        @Override
        public Class<String> getDataClass() {
            return String.class;
        }

        @Override
        public String encode(E model) {
            return model.name();
        }

        @Override
        public E decode(String data) {
            return enumsByName.get(data);
        }
    };
}

From source file:com.telefonica.iot.cygnus.management.StatsHandlers.java

/**
 * Handles PUT /v1/stats (reset)./*  w w w . j  a  v a2s  . com*/
 * @param response
 * @param sources
 * @param channels
 * @param sinks
 * @throws IOException
 */
public static void put(HttpServletResponse response, ImmutableMap<String, SourceRunner> sources,
        ImmutableMap<String, Channel> channels, ImmutableMap<String, SinkRunner> sinks) throws IOException {
    response.setContentType("application/json; charset=utf-8");

    for (String key : sources.keySet()) {
        Source source;
        HTTPSourceHandler handler;

        try {
            SourceRunner sr = sources.get(key);
            source = sr.getSource();
            Field f = source.getClass().getDeclaredField("handler");
            f.setAccessible(true);
            handler = (HTTPSourceHandler) f.get(source);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
                | SecurityException e) {
            LOGGER.error("There was a problem when getting a sink. Details: " + e.getMessage());
            continue;
        } // try catch

        if (handler instanceof CygnusHandler) {
            CygnusHandler ch = (CygnusHandler) handler;
            ch.setNumProcessedEvents(0);
            ch.setNumReceivedEvents(0);
        } // if
    } // for

    for (String key : channels.keySet()) {
        Channel channel = channels.get(key);

        if (channel instanceof CygnusChannel) {
            CygnusChannel cc = (CygnusChannel) channel;
            cc.setNumPutsOK(0);
            cc.setNumPutsFail(0);
            cc.setNumTakesOK(0);
            cc.setNumTakesFail(0);
        } // if
    } // for

    for (String key : sinks.keySet()) {
        Sink sink;

        try {
            SinkRunner sr = sinks.get(key);
            SinkProcessor sp = sr.getPolicy();
            Field f = sp.getClass().getDeclaredField("sink");
            f.setAccessible(true);
            sink = (Sink) f.get(sp);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
                | SecurityException e) {
            LOGGER.error("There was a problem when getting a sink. Details: " + e.getMessage());
            continue;
        } // try catch

        if (sink instanceof CygnusSink) {
            CygnusSink cs = (CygnusSink) sink;
            cs.setNumProcessedEvents(0);
            cs.setNumPersistedEvents(0);
        } // if
    } // for

    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().println("{\"success\":\"true\"}");
    LOGGER.debug("Statistics reseted");
}

From source file:ome.services.blitz.repo.path.FilePathRestrictions.java

/**
 * Combine sets of rules to form a set that satisfies them all.
 * @param rules at least one set of rules
 * @return the intersection of the given rules
 *//*w  ww  .  j  a  v a 2 s.  com*/
private static FilePathRestrictions combineRules(FilePathRestrictions... rules) {
    if (rules.length == 0) {
        throw new IllegalArgumentException("cannot combine an empty list of rules");
    }

    int index = 0;
    FilePathRestrictions product = rules[index++];

    while (index < rules.length) {
        final FilePathRestrictions toCombine = rules[index++];

        final Set<Character> safeCharacters = Sets.intersection(product.safeCharacters,
                toCombine.safeCharacters);

        if (safeCharacters.isEmpty()) {
            throw new IllegalArgumentException("cannot combine safe characters");
        }

        final Set<Integer> allKeys = Sets.union(product.transformationMatrix.keySet(),
                toCombine.transformationMatrix.keySet());
        final ImmutableMap<Integer, Collection<Integer>> productMatrixMap = product.transformationMatrix
                .asMap();
        final ImmutableMap<Integer, Collection<Integer>> toCombineMatrixMap = toCombine.transformationMatrix
                .asMap();
        final SetMultimap<Integer, Integer> newTransformationMatrix = HashMultimap.create();

        for (final Integer key : allKeys) {
            final Collection<Integer> values;
            if (!productMatrixMap.containsKey(key)) {
                values = toCombineMatrixMap.get(key);
            } else if (!toCombineMatrixMap.containsKey(key)) {
                values = productMatrixMap.get(key);
            } else {
                final Set<Integer> valuesSet = new HashSet<Integer>(productMatrixMap.get(key));
                valuesSet.retainAll(toCombineMatrixMap.get(key));
                if (valuesSet.isEmpty()) {
                    throw new IllegalArgumentException(
                            "cannot combine transformations for Unicode code point " + key);
                }
                values = valuesSet;
            }
            for (final Integer value : values) {
                newTransformationMatrix.put(key, value);
            }
        }

        final SetMultimap<Integer, Integer> entriesRemoved = HashMultimap.create();
        boolean transitiveClosing;
        do {
            transitiveClosing = false;
            for (final Entry<Integer, Integer> transformation : newTransformationMatrix.entries()) {
                final int to = transformation.getValue();
                if (newTransformationMatrix.containsKey(to)) {
                    final int from = transformation.getKey();
                    if (!entriesRemoved.put(from, to)) {
                        throw new IllegalArgumentException(
                                "cyclic transformation involving Unicode code point " + from);
                    }
                    newTransformationMatrix.remove(from, to);
                    newTransformationMatrix.putAll(from, newTransformationMatrix.get(to));
                    transitiveClosing = true;
                    break;
                }
            }
        } while (transitiveClosing);

        product = new FilePathRestrictions(newTransformationMatrix,
                Sets.union(product.unsafePrefixes, toCombine.unsafePrefixes),
                Sets.union(product.unsafeSuffixes, toCombine.unsafeSuffixes),
                Sets.union(product.unsafeNames, toCombine.unsafeNames), safeCharacters);
    }
    return product;
}

From source file:com.google.template.soy.shared.internal.ModuleUtils.java

/**
 * Given the set of all Soy function implementations, a specific Soy function type (subtype of
 * SoyFunction) to look for, another Soy function type to look for that is an equivalent
 * deprecated version of the specific Soy function type, and an adapt function for adapting the
 * deprecated type to the specific type, finds the Soy functions that implement either type and
 * returns them in the form of a map from function name to function, where the functions with
 * the deprecated type have been adapted using the adapt function.
 *
 * @param <T> The specific Soy function type to look for.
 * @param <D> The equivalent deprecated Soy function type to also look for.
 * @param soyFunctionsSet The set of all Soy functions.
 * @param specificSoyFunctionType The class of the specific Soy function type to look for.
 * @param equivDeprecatedSoyFunctionType The class of the equivalent deprecated Soy function
 *     type to also look for.//from w w  w .  ja v  a  2  s  .c om
 * @param adaptFn The adapt function that adapts the deprecated type to the specific type.
 * @return A map of the relevant specific Soy functions (name to function).
 */
public static <T extends SoyFunction, D extends SoyFunction> ImmutableMap<String, T> buildSpecificSoyFunctionsMapWithAdaptation(
        Set<SoyFunction> soyFunctionsSet, Class<T> specificSoyFunctionType,
        Class<D> equivDeprecatedSoyFunctionType, Function<D, T> adaptFn) {

    ImmutableMap<String, T> tMap = buildSpecificSoyFunctionsMap(soyFunctionsSet, specificSoyFunctionType);
    ImmutableMap<String, D> dMap = buildSpecificSoyFunctionsMap(soyFunctionsSet,
            equivDeprecatedSoyFunctionType);

    ImmutableMap.Builder<String, T> resultMapBuilder = ImmutableMap.builder();
    resultMapBuilder.putAll(tMap);
    for (String functionName : dMap.keySet()) {
        if (tMap.containsKey(functionName)) {
            if (tMap.get(functionName).equals(dMap.get(functionName))) {
                throw new IllegalStateException(String.format(
                        "Found function named '%s' that implements both %s and"
                                + " %s -- please remove the latter deprecated interface.",
                        functionName, specificSoyFunctionType.getSimpleName(),
                        equivDeprecatedSoyFunctionType.getSimpleName()));
            } else {
                throw new IllegalStateException(String.format(
                        "Found two functions with the same name '%s', one implementing %s and the"
                                + " other implementing %s",
                        functionName, specificSoyFunctionType.getSimpleName(),
                        equivDeprecatedSoyFunctionType.getSimpleName()));
            }
        }
        resultMapBuilder.put(functionName, adaptFn.apply(dMap.get(functionName)));
    }
    return resultMapBuilder.build();
}

From source file:com.google.polymer.JsRenamer.java

/**
 * Renames path expressions without using the Closure Compiler for parsing.
 * @param renameMap A mapping from symbol to renamed symbol.
 * @param pathExpression The path expression to rename.
 * @return The renamed path expression.// w w  w . j av  a 2  s.c  o m
 */
private static String renamePolymerPathExpression(ImmutableMap<String, String> renameMap,
        String pathExpression) {
    if (renameMap.containsKey(pathExpression)) {
        return renameMap.get(pathExpression);
    } else if (pathExpression.contains(".")) {
        String[] components = PROPERTY_EXPRESSION_SPLITTER.splitToList(pathExpression).toArray(new String[0]);
        for (int i = 0; i < components.length; i++) {
            components[i] = renamePolymerPathExpression(renameMap, components[i]);
        }
        return PROPERTY_EXPRESSION_JOINER.join(components);
    }
    return pathExpression;
}

From source file:com.cloudera.hadoop.hdfs.nfs.nfs4.attrs.Attribute.java

public static Bitmap setAttrs(NFS4Handler server, Session session, Bitmap requestedAttrs,
        ImmutableMap<Integer, Attribute> attrValues, FileSystem fs, FileStatus fileStatus, StateID stateID)
        throws NFS4Exception, IOException {
    Bitmap responseAttrs = new Bitmap();
    int size = requestedAttrs.size();
    for (int bitIndex = 0; bitIndex < size; bitIndex++) {
        if (requestedAttrs.isSet(bitIndex)) {
            AttributeHandler<Attribute> handler = getHandler(bitIndex);
            if (handler.set(server, session, fs, fileStatus, stateID, attrValues.get(bitIndex))) {
                responseAttrs.set(bitIndex);
            }/*from  w w  w.ja v  a2  s .c  om*/
        }
    }
    return requestedAttrs;
}

From source file:com.google.template.soy.shared.internal.ModuleUtils.java

/**
 * Given the set of all Soy directive implementations, a specific Soy directive type (subtype of
 * SoyPrintDirective) to look for, another Soy directive type to look for that is an equivalent
 * deprecated version of the specific Soy directive type, and an adapt function for adapting the
 * deprecated type to the specific type, finds the Soy directives that implement either type and
 * returns them in the form of a map from directive name to directive, where the directives with
 * the deprecated type have been adapted using the adapt function.
 *
 * @param <T> The specific Soy directive type to look for.
 * @param <D> The equivalent deprecated Soy directive type to also look for.
 * @param soyDirectivesSet The set of all Soy directives.
 * @param specificSoyDirectiveType The class of the specific Soy directive type to look for.
 * @param equivDeprecatedSoyDirectiveType The class of the equivalent deprecated Soy directive
 *     type to also look for.//from   www  . j a v  a2 s  .  c o m
 * @param adaptFn The adapt function that adapts the deprecated type to the specific type.
 * @return A map of the relevant specific Soy directives (name to directive).
 */
public static <T extends SoyPrintDirective, D extends SoyPrintDirective> ImmutableMap<String, T> buildSpecificSoyDirectivesMapWithAdaptation(
        Set<SoyPrintDirective> soyDirectivesSet, Class<T> specificSoyDirectiveType,
        Class<D> equivDeprecatedSoyDirectiveType, Function<D, T> adaptFn) {

    ImmutableMap<String, T> tMap = buildSpecificSoyDirectivesMap(soyDirectivesSet, specificSoyDirectiveType);
    ImmutableMap<String, D> dMap = buildSpecificSoyDirectivesMap(soyDirectivesSet,
            equivDeprecatedSoyDirectiveType);

    ImmutableMap.Builder<String, T> resultMapBuilder = ImmutableMap.builder();
    resultMapBuilder.putAll(tMap);
    for (String directiveName : dMap.keySet()) {
        if (tMap.containsKey(directiveName)) {
            if (tMap.get(directiveName).equals(dMap.get(directiveName))) {
                throw new IllegalStateException(String.format(
                        "Found print directive named '%s' that implements both %s and"
                                + " %s -- please remove the latter deprecated interface.",
                        directiveName, specificSoyDirectiveType.getSimpleName(),
                        equivDeprecatedSoyDirectiveType.getSimpleName()));
            } else {
                throw new IllegalStateException(String.format(
                        "Found two print directives with the same name '%s', one implementing %s and the"
                                + " other implementing %s",
                        directiveName, specificSoyDirectiveType.getSimpleName(),
                        equivDeprecatedSoyDirectiveType.getSimpleName()));
            }
        }
        resultMapBuilder.put(directiveName, adaptFn.apply(dMap.get(directiveName)));
    }
    return resultMapBuilder.build();
}

From source file:com.google.api.codegen.config.ResourceNameMessageConfigs.java

@Nullable
public static ResourceNameMessageConfigs createMessageResourceTypesConfig(Model model, ConfigProto configProto,
        String defaultPackage) {/*from  w w  w .  j a va 2 s. c  om*/
    ImmutableMap.Builder<String, ResourceNameMessageConfig> builder = ImmutableMap.builder();
    for (ResourceNameMessageConfigProto messageResourceTypesProto : configProto
            .getResourceNameGenerationList()) {
        ResourceNameMessageConfig messageResourceTypeConfig = ResourceNameMessageConfig
                .createResourceNameMessageConfig(model.getDiagCollector(), messageResourceTypesProto,
                        defaultPackage);
        builder.put(messageResourceTypeConfig.messageName(), messageResourceTypeConfig);
    }
    ImmutableMap<String, ResourceNameMessageConfig> messageResourceTypeConfigMap = builder.build();

    ListMultimap<String, FieldModel> fieldsByMessage = ArrayListMultimap.create();
    Set<String> seenProtoFiles = new HashSet<>();
    for (ProtoFile protoFile : model.getFiles()) {
        if (!seenProtoFiles.contains(protoFile.getSimpleName())) {
            seenProtoFiles.add(protoFile.getSimpleName());
            for (MessageType msg : protoFile.getMessages()) {
                ResourceNameMessageConfig messageConfig = messageResourceTypeConfigMap.get(msg.getFullName());
                if (messageConfig == null) {
                    continue;
                }
                for (Field field : msg.getFields()) {
                    if (messageConfig.getEntityNameForField(field.getSimpleName()) != null) {
                        fieldsByMessage.put(msg.getFullName(), new ProtoField(field));
                    }
                }
            }
        }
    }
    return new AutoValue_ResourceNameMessageConfigs(messageResourceTypeConfigMap, fieldsByMessage);
}

From source file:com.google.polymer.JsRenamer.java

/**
 * Renames Polymer property changed object property identifiers (*Changed properties).
 * @param renameMap A mapping from symbol to renamed symbol.
 * @param node The string node containing the property changed identifier.
 *///from w ww  . j  a  va 2s.c om
private static void renamePolymerPropertyStringNode(ImmutableMap<String, String> renameMap, Node node) {
    String name = node.getString();
    if (renameMap.containsKey(name)) {
        node.setString(renameMap.get(name));
    } else if (name.endsWith(CHANGED_SUFFIX)) {
        String basename = name.substring(0, name.length() - CHANGED_SUFFIX.length());
        if (renameMap.containsKey(basename)) {
            node.setString(renameMap.get(basename) + CHANGED_SUFFIX);
        }
    }
}

From source file:org.elasticsearch.index.analysis.Analysis.java

private static CharArraySet resolveNamedWords(Collection<String> words, ImmutableMap<String, Set<?>> namedWords,
        Version version, boolean ignoreCase) {
    if (namedWords == null) {
        return new CharArraySet(version, words, ignoreCase);
    }/*from  w  w  w . j ava2s.co  m*/
    CharArraySet setWords = new CharArraySet(version, words.size(), ignoreCase);
    for (String word : words) {
        if (namedWords.containsKey(word)) {
            setWords.addAll(namedWords.get(word));
        } else {
            setWords.add(word);
        }
    }
    return setWords;
}