Example usage for com.google.common.collect ImmutableMap.Builder put

List of usage examples for com.google.common.collect ImmutableMap.Builder put

Introduction

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

Prototype

public final V put(K k, V v) 

Source Link

Usage

From source file:com.google.devtools.build.lib.bazel.Bazel.java

/**
 * Builds the standard build info map from the loaded properties. The returned value is the list
 * of "build.*" properties from the build-data.properties file. The final key is the original one
 * striped, dot replaced with a space and with first letter capitalized. If the file fails to
 * load the returned map is empty.// w w  w  . j  av a2 s .  c o m
 */
private static ImmutableMap<String, String> tryGetBuildInfo() {
    try (InputStream in = Bazel.class.getResourceAsStream(BUILD_DATA_PROPERTIES)) {
        if (in == null) {
            return ImmutableMap.of();
        }
        Properties props = new Properties();
        props.load(in);
        ImmutableMap.Builder<String, String> buildData = ImmutableMap.builder();
        for (Object key : props.keySet()) {
            String stringKey = key.toString();
            if (stringKey.startsWith("build.")) {
                // build.label -> Build label, build.timestamp.as.int -> Build timestamp as int
                String buildDataKey = "B" + stringKey.substring(1).replace('.', ' ');
                buildData.put(buildDataKey, props.getProperty(stringKey, ""));
            }
        }
        return buildData.build();
    } catch (IOException ignored) {
        return ImmutableMap.of();
    }
}

From source file:co.cask.cdap.hive.objectinspector.ObjectInspectorFactory.java

private static ObjectInspector getReflectionObjectInspectorNoCache(Type t) {
    if (t instanceof GenericArrayType) {
        GenericArrayType at = (GenericArrayType) t;
        return getStandardListObjectInspector(getReflectionObjectInspector(at.getGenericComponentType()));
    }//  w w  w.  ja v a  2s. c o  m

    Map<TypeVariable, Type> genericTypes = null;
    if (t instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) t;
        Type rawType = pt.getRawType();
        // Collection?
        if (Collection.class.isAssignableFrom((Class<?>) rawType)) {
            return getStandardListObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0]));
        }
        // Map?
        if (Map.class.isAssignableFrom((Class<?>) rawType)) {
            return getStandardMapObjectInspector(getReflectionObjectInspector(pt.getActualTypeArguments()[0]),
                    getReflectionObjectInspector(pt.getActualTypeArguments()[1]));
        }
        // Otherwise convert t to RawType so we will fall into the following if block.
        t = rawType;

        ImmutableMap.Builder<TypeVariable, Type> builder = ImmutableMap.builder();
        for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
            builder.put(((Class<?>) t).getTypeParameters()[i], pt.getActualTypeArguments()[i]);
        }
        genericTypes = builder.build();
    }

    // Must be a class.
    if (!(t instanceof Class)) {
        throw new RuntimeException(ObjectInspectorFactory.class.getName() + " internal error:" + t);
    }
    Class<?> c = (Class<?>) t;

    // Java Primitive Type?
    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaType(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(
                PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaType(c).primitiveCategory);
    }

    // Java Primitive Class?
    if (PrimitiveObjectInspectorUtils.isPrimitiveJavaClass(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(
                PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveJavaClass(c).primitiveCategory);
    }

    // Primitive Writable class?
    if (PrimitiveObjectInspectorUtils.isPrimitiveWritableClass(c)) {
        return PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(
                PrimitiveObjectInspectorUtils.getTypeEntryFromPrimitiveWritableClass(c).primitiveCategory);
    }

    // Enum class?
    if (Enum.class.isAssignableFrom(c)) {
        return PrimitiveObjectInspectorFactory
                .getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING);
    }

    // Array
    if (c.isArray()) {
        return getStandardListObjectInspector(getReflectionObjectInspector(c.getComponentType()));
    }

    // Must be struct because List and Map need to be ParameterizedType
    Preconditions.checkState(!List.class.isAssignableFrom(c));
    Preconditions.checkState(!Map.class.isAssignableFrom(c));

    Preconditions.checkState(!c.isInterface(), "Cannot inspect an interface.");

    ReflectionStructObjectInspector oi = new ReflectionStructObjectInspector();
    // put it into the cache BEFORE it is initialized to make sure we can catch
    // recursive types.
    objectInspectorCache.put(t, oi);
    Field[] fields = ObjectInspectorUtils.getDeclaredNonStaticFields(c);
    List<ObjectInspector> structFieldObjectInspectors = new ArrayList<>(fields.length);
    for (int i = 0; i < fields.length; i++) {
        // Exclude transient fields and synthetic fields. The latter has the effect of excluding the implicit
        // "this" pointer present in nested classes and that references the parent.
        if (Modifier.isTransient(fields[i].getModifiers()) || fields[i].isSynthetic()) {
            continue;
        }
        if (!oi.shouldIgnoreField(fields[i].getName())) {
            Type newType = fields[i].getGenericType();
            if (newType instanceof TypeVariable) {
                Preconditions.checkNotNull(genericTypes, "Type was not recognized as a parameterized type.");
                Preconditions.checkNotNull(genericTypes.get(newType),
                        "Generic type " + newType + " not a parameter of class " + c);
                newType = genericTypes.get(newType);
            }
            structFieldObjectInspectors.add(getReflectionObjectInspector(newType));
        }
    }
    oi.init(c, structFieldObjectInspectors);
    return oi;
}

From source file:com.github.rinde.jaamas17.ResultWriter.java

static void addSimOutputs(ImmutableMap.Builder<Enum<?>, Object> map, SimulationResult sr,
        Gendreau06ObjectiveFunction objFunc) {
    if (sr.getResultObject() instanceof FailureStrategy) {
        map.put(OutputFields.COST, -1).put(OutputFields.TRAVEL_TIME, -1).put(OutputFields.TARDINESS, -1)
                .put(OutputFields.OVER_TIME, -1).put(OutputFields.IS_VALID, false)
                .put(OutputFields.COMP_TIME, -1).put(OutputFields.NUM_REAUCTIONS, -1)
                .put(OutputFields.NUM_UNSUC_REAUCTIONS, -1).put(OutputFields.NUM_FAILED_REAUCTIONS, -1);
    } else {//from w  w w  .j a  v a  2 s.c om
        final SimResult ei = (SimResult) sr.getResultObject();
        final StatisticsDTO stats = ei.getStats();
        map.put(OutputFields.COST, objFunc.computeCost(stats))
                .put(OutputFields.TRAVEL_TIME, objFunc.travelTime(stats))
                .put(OutputFields.TARDINESS, objFunc.tardiness(stats))
                .put(OutputFields.OVER_TIME, objFunc.overTime(stats))
                .put(OutputFields.IS_VALID, objFunc.isValidResult(stats))
                .put(OutputFields.COMP_TIME, stats.computationTime);

        if (ei.getAuctionStats().isPresent()) {
            final AuctionStats aStats = ei.getAuctionStats().get();
            map.put(OutputFields.NUM_REAUCTIONS, aStats.getNumReauctions())
                    .put(OutputFields.NUM_UNSUC_REAUCTIONS, aStats.getNumUnsuccesfulReauctions())
                    .put(OutputFields.NUM_FAILED_REAUCTIONS, aStats.getNumFailedReauctions());
        } else {
            map.put(OutputFields.NUM_REAUCTIONS, 0).put(OutputFields.NUM_UNSUC_REAUCTIONS, 0)
                    .put(OutputFields.NUM_FAILED_REAUCTIONS, 0);
        }

        if (!objFunc.isValidResult(stats)) {
            System.err.println("WARNING: FOUND AN INVALID RESULT: ");
            System.err.println(map.build());
        }
    }
}

From source file:org.lenskit.data.dao.MapItemNameDAO.java

/**
 * Read an item list DAO from a file.//from   w w w . ja  v  a 2  s . c  om
 * @param file A file of item IDs, one per line.
 * @param skipLines The number of initial header to skip
 * @return The item list DAO.
 * @throws java.io.IOException if there is an error reading the list of items.
 */
public static MapItemNameDAO fromCSVFile(File file, int skipLines) throws IOException {
    Preconditions.checkArgument(skipLines >= 0, "cannot skip negative lines");
    LineStream stream = LineStream.openFile(file, CompressionMode.AUTO);
    try {
        ObjectStreams.consume(skipLines, stream);
        ImmutableMap.Builder<Long, String> names = ImmutableMap.builder();
        StrTokenizer tok = StrTokenizer.getCSVInstance();
        for (String line : stream) {
            tok.reset(line);
            long item = Long.parseLong(tok.next());
            String title = tok.nextToken();
            if (title != null) {
                names.put(item, title);
            }
        }
        return new MapItemNameDAO(names.build());
    } catch (NoSuchElementException ex) {
        throw new IOException(String.format("%s:%s: not enough columns", file, stream.getLineNumber()), ex);
    } catch (NumberFormatException ex) {
        throw new IOException(String.format("%s:%s: id not an integer", file, stream.getLineNumber()), ex);
    } finally {
        stream.close();
    }
}

From source file:com.spectralogic.dsbrowser.gui.services.tasks.Ds3GetJob.java

public static ImmutableMap<String, Path> getFolderMap(final List<Ds3TreeTableValueCustom> selectedItems) {
    final ImmutableList<Ds3TreeTableValueCustom> folderList = selectedItems.stream()
            .filter(value -> !value.getType().equals(Ds3TreeTableValue.Type.File))
            .collect(GuavaCollectors.immutableList());
    final ImmutableMap.Builder<String, Path> fileMap = ImmutableMap.builder();
    folderList.forEach(folder -> {/*  w ww. java  2 s. c  om*/
        fileMap.put(folder.getFullName(), Paths.get(StringConstants.FORWARD_SLASH));
    });
    return fileMap.build();
}

From source file:ru.org.linux.search.SearchController.java

@ModelAttribute("intervals")
public static Map<SearchViewer.SearchInterval, String> getIntervals() {
    ImmutableMap.Builder<SearchViewer.SearchInterval, String> builder = ImmutableSortedMap.naturalOrder();

    for (SearchViewer.SearchInterval value : SearchViewer.SearchInterval.values()) {
        builder.put(value, value.getTitle());
    }//from   ww  w.j  a  v a  2 s.  com

    return builder.build();
}

From source file:com.android.contacts.model.account.AccountTypeProvider.java

private static ImmutableMap<String, AuthenticatorDescription> onlyContactSyncable(
        AuthenticatorDescription[] auths, SyncAdapterType[] syncTypes) {
    final Set<String> mContactSyncableTypes = new HashSet<>();
    for (SyncAdapterType type : syncTypes) {
        if (type.authority.equals(ContactsContract.AUTHORITY)) {
            mContactSyncableTypes.add(type.accountType);
        }//from  w  ww  .j  a v  a 2 s . c o m
    }

    final ImmutableMap.Builder<String, AuthenticatorDescription> builder = ImmutableMap.builder();
    for (AuthenticatorDescription auth : auths) {
        if (mContactSyncableTypes.contains(auth.type)) {
            builder.put(auth.type, auth);
        }
    }
    return builder.build();
}

From source file:com.google.caliper.config.CaliperConfig.java

private static ImmutableMap<Class<? extends ResultProcessor>, ResultProcessorConfig> findResultProcessorConfigs(
        ImmutableMap<String, String> resultsProperties) throws InvalidConfigurationException {
    ImmutableBiMap<String, Class<? extends ResultProcessor>> processorToClass = mapGroupNamesToClasses(
            resultsProperties, ResultProcessor.class);
    ImmutableMap.Builder<Class<? extends ResultProcessor>, ResultProcessorConfig> builder = ImmutableMap
            .builder();//from   w  w  w.  j a va 2 s.c o m
    for (Entry<String, Class<? extends ResultProcessor>> entry : processorToClass.entrySet()) {
        builder.put(entry.getValue(), getResultProcessorConfig(resultsProperties, entry.getKey()));
    }
    return builder.build();
}

From source file:edu.mit.streamjit.util.CollectionUtils.java

/**
 * Returns the union of the given maps, using the given function to merge
 * values for the same key.  The function is called for all keys with a list
 * of the values of the maps in the order the maps were given.  Maps that do
 * not contain the key are not represented in the list.  The function's
 * return value is used as the value in the union map.
 * TODO: the generics don't seem right here; I should be able to use e.g.
 * a Collection<Comparable> in place of List<Integer> for the middle arg.
 * Note that the above overload permits that and forwards to this one!
 * @param <K> the key type of the returned map
 * @param <V> the value type of the returned map
 * @param <X> the value type of the input map(s)
 * @param merger the function used to merge values for the same key
 * @param maps the maps/*from w w w .  j a v  a2  s  . co  m*/
 * @return a map containing all the keys in the given maps
 */
public static <K, V, X> ImmutableMap<K, V> union(
        Maps.EntryTransformer<? super K, ? super List<X>, ? extends V> merger,
        List<? extends Map<? extends K, ? extends X>> maps) {
    ImmutableSet.Builder<K> keys = ImmutableSet.builder();
    for (Map<? extends K, ? extends X> m : maps)
        keys.addAll(m.keySet());

    ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
    for (K k : keys.build()) {
        ImmutableList.Builder<X> values = ImmutableList.builder();
        for (Map<? extends K, ? extends X> m : maps)
            if (m.containsKey(k))
                values.add(m.get(k));
        builder.put(k, merger.transformEntry(k, values.build()));
    }
    return builder.build();
}

From source file:gobblin.hive.metastore.HiveMetaStoreEventHelper.java

private static Map<String, String> getAdditionalMetadata(HiveSpec spec, Optional<Exception> error) {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder()
            .put(DB_NAME, spec.getTable().getDbName()).put(TABLE_NAME, spec.getTable().getTableName())
            .put("Path", spec.getPath().toString());

    if (spec.getPartition().isPresent()) {
        builder.put(PARTITIONS, spec.getPartition().get().toString());
    }//w ww. j a  v a2 s . co  m

    if (error.isPresent()) {
        builder.put(ERROR_MESSAGE, error.get().getMessage());
    }

    return builder.build();
}