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:com.facebook.buck.cxx.CxxPreprocessStep.java

@VisibleForTesting
protected static Function<String, String> createOutputLineProcessor(final Path workingDir,
        final ImmutableMap<Path, Path> replacementPaths, final Optional<DebugPathSanitizer> sanitizer) {

    return new Function<String, String>() {

        private final Pattern lineMarkers = Pattern.compile("^# (?<num>\\d+) \"(?<path>[^\"]+)\"(?<rest>.*)?$");

        @Override/*from  w w  w .  jav  a  2  s . co  m*/
        public String apply(String line) {
            if (line.startsWith("# ")) {
                Matcher m = lineMarkers.matcher(line);
                if (m.find()) {
                    String originalPath = m.group("path");
                    String replacementPath = originalPath;

                    replacementPath = Optional.fromNullable(replacementPaths.get(Paths.get(replacementPath)))
                            .transform(Functions.toStringFunction()).or(replacementPath);

                    if (sanitizer.isPresent()) {
                        replacementPath = sanitizer.get().sanitize(Optional.of(workingDir), replacementPath);
                    }

                    if (!originalPath.equals(replacementPath)) {
                        String num = m.group("num");
                        String rest = m.group("rest");
                        return "# " + num + " \"" + replacementPath + "\"" + rest;
                    }
                }
            }
            return line;
        }

    };
}

From source file:com.facebook.buck.distributed.DistributedCellProviderFactory.java

public static CellProvider create(DistBuildCellParams rootCell,
        ImmutableMap<Path, DistBuildCellParams> cellParams, CellPathResolver rootCellPathResolver,
        UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) {
    Map<String, Path> cellPaths = cellParams.values().stream().filter(p -> p.getCanonicalName().isPresent())
            .collect(Collectors.toMap(p -> p.getCanonicalName().get(), p -> p.getFilesystem().getRootPath()));
    ImmutableSet<String> declaredCellNames = ImmutableSet.copyOf(cellPaths.keySet());
    Path rootCellPath = rootCell.getFilesystem().getRootPath();
    DefaultCellPathResolver rootCellResolver = DefaultCellPathResolver.of(rootCellPath, cellPaths);

    return new CellProvider(cellProvider -> CacheLoader.from(cellPath -> {
        DistBuildCellParams cellParam = Objects.requireNonNull(cellParams.get(cellPath),
                "This should only be called for secondary cells.");
        Path currentCellRoot = cellParam.getFilesystem().getRootPath();
        Preconditions.checkState(!currentCellRoot.equals(rootCellPath));
        CellPathResolver currentCellResolver = rootCellResolver;
        // The CellPathResolverView is required because it makes the
        // [RootPath<->CanonicalName] resolver methods non-symmetrical to handle the
        // fact/* www  . j  av a  2 s .  c  om*/
        // that relative main cell from inside a secondary cell resolves actually to
        // secondary cell. If the DefaultCellPathResolver is used, then it would return
        // a BuildTarget as if it belonged to the main cell.
        currentCellResolver = new CellPathResolverView(rootCellResolver, declaredCellNames, currentCellRoot);
        CellPathResolver cellPathResolverForParser = currentCellResolver;
        BuckConfig configWithResolver = cellParam.getConfig()
                .withBuildTargetParser(buildTargetName -> unconfiguredBuildTargetFactory
                        .create(cellPathResolverForParser, buildTargetName));
        RuleKeyConfiguration ruleKeyConfiguration = ConfigRuleKeyConfigurationFactory.create(configWithResolver,
                cellParam.getBuckModuleManager());
        ToolchainProvider toolchainProvider = new DefaultToolchainProvider(cellParam.getPluginManager(),
                cellParam.getEnvironment(), configWithResolver, cellParam.getFilesystem(),
                cellParam.getProcessExecutor(), cellParam.getExecutableFinder(), ruleKeyConfiguration);

        return ImmutableCell.of(ImmutableSortedSet.copyOf(cellParams.keySet()),
                // Distributed builds don't care about cell names, use a sentinel value that
                // will show up if it actually does care about them.
                cellParam.getCanonicalName(), cellParam.getFilesystem(), configWithResolver, cellProvider,
                toolchainProvider, ruleKeyConfiguration, currentCellResolver);
    }), cellProvider -> RootCellFactory.create(cellProvider, rootCellResolver, rootCellPathResolver,
            rootCell.getFilesystem(), rootCell.getBuckModuleManager(), rootCell.getPluginManager(),
            rootCell.getConfig(), rootCell.getEnvironment(), rootCell.getProcessExecutor(),
            rootCell.getExecutableFinder()));
}

From source file:org.fixb.meta.FixMetaScanner.java

private static int orderFixFields(Constructor<?> constructor, ImmutableMap<Integer, FixFieldMeta> fixFields,
        FixFieldMeta[] ordered, MutableFixMetaDictionary dictionary, int offset) {
    final Annotation[][] annotations = constructor.getParameterAnnotations();
    for (int i = 0; i < annotations.length; i++) {
        if (hasFixAnnotation(annotations[i], FixBlock.class)) {
            final Class<?>[] paramTypes = constructor.getParameterTypes();
            for (FixFieldMeta fixFieldMeta : dictionary.getComponentMeta(paramTypes[i]).getFields()) {
                ordered[offset++] = fixFields.get(fixFieldMeta.getTag());
            }/*from   w w  w .j a  v  a2  s  . co m*/
        } else {
            final Optional<Integer> tag = getFixTagFromAnnotations(annotations[i]);
            if (!tag.isPresent()) {
                throw new FixException("Some constructor parameters don't have FIX mapping in class ["
                        + constructor.getDeclaringClass().getName() + "].");
            }

            final FixFieldMeta fixFieldMeta = fixFields.get(tag.get());
            if (fixFieldMeta == null) {
                throw new FixException("No field with tag [" + tag.get()
                        + "] found, however constructor parameters exist in class ["
                        + constructor.getDeclaringClass().getName() + "].");
            }

            ordered[offset++] = fixFieldMeta;
        }
    }

    return offset;
}

From source file:com.facebook.buck.android.AndroidNativeLibsPackageableGraphEnhancer.java

private static ImmutableMap<StripLinkable, StrippedObjectDescription> generateStripRules(
        BuildRuleParams buildRuleParams, SourcePathRuleFinder ruleFinder, BuildRuleResolver ruleResolver,
        BuildTarget appRuleTarget, ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms,
        ImmutableMap<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> libs) {
    ImmutableMap.Builder<StripLinkable, StrippedObjectDescription> result = ImmutableMap.builder();
    for (Map.Entry<Pair<NdkCxxPlatforms.TargetCpuType, String>, SourcePath> entry : libs.entrySet()) {
        SourcePath sourcePath = entry.getValue();
        NdkCxxPlatforms.TargetCpuType targetCpuType = entry.getKey().getFirst();

        NdkCxxPlatform platform = Preconditions.checkNotNull(nativePlatforms.get(targetCpuType));

        // To be safe, default to using the app rule target as the base for the strip rule.
        // This will be used for stripping the C++ runtime.  We could use something more easily
        // shareable (like just using the app's containing directory, or even the repo root),
        // but stripping the C++ runtime is pretty fast, so just keep the safe old behavior for now.
        BuildTarget baseBuildTarget = appRuleTarget;
        // But if we're stripping a cxx_library, use that library as the base of the target
        // to allow sharing the rule between all apps that depend on it.
        if (sourcePath instanceof BuildTargetSourcePath) {
            baseBuildTarget = ((BuildTargetSourcePath) sourcePath).getTarget();
        }//from  w w w  . j  a  va  2s.c o  m

        String sharedLibrarySoName = entry.getKey().getSecond();
        BuildTarget targetForStripRule = BuildTarget.builder(baseBuildTarget)
                .addFlavors(ImmutableFlavor.of("android-strip"))
                .addFlavors(ImmutableFlavor.of(Flavor.replaceInvalidCharacters(sharedLibrarySoName)))
                .addFlavors(ImmutableFlavor.of(Flavor.replaceInvalidCharacters(targetCpuType.name()))).build();

        Optional<BuildRule> previouslyCreated = ruleResolver.getRuleOptional(targetForStripRule);
        StripLinkable stripLinkable;
        if (previouslyCreated.isPresent()) {
            stripLinkable = (StripLinkable) previouslyCreated.get();
        } else {
            BuildRuleParams paramsForStripLinkable = buildRuleParams.copyWithChanges(targetForStripRule,
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                            .addAll(ruleFinder.filterBuildRuleInputs(ImmutableList.of(sourcePath))).build()),
                    /* extraDeps */ Suppliers.ofInstance(ImmutableSortedSet.of()));

            stripLinkable = new StripLinkable(paramsForStripLinkable, platform.getCxxPlatform().getStrip(),
                    sourcePath, sharedLibrarySoName);

            ruleResolver.addToIndex(stripLinkable);
        }
        result.put(stripLinkable,
                StrippedObjectDescription.builder()
                        .setSourcePath(new BuildTargetSourcePath(stripLinkable.getBuildTarget()))
                        .setStrippedObjectName(sharedLibrarySoName).setTargetCpuType(targetCpuType).build());
    }
    return result.build();
}

From source file:com.facebook.buck.features.apple.project.SchemeGenerator.java

public static Element serializeEnvironmentVariables(Document doc,
        ImmutableMap<String, String> environmentVariables) {
    Element rootElement = doc.createElement("EnvironmentVariables");
    for (String variableKey : environmentVariables.keySet()) {
        Element variableElement = doc.createElement("EnvironmentVariable");
        variableElement.setAttribute("key", variableKey);
        variableElement.setAttribute("value", environmentVariables.get(variableKey));
        variableElement.setAttribute("isEnabled", "YES");
        rootElement.appendChild(variableElement);
    }// w  ww.j  a  v a 2s .c o m
    return rootElement;
}

From source file:com.googlecode.blaisemath.sketch.SketchActions.java

public static void alignHorizontal(Set<Graphic<Graphics2D>> selection) {
    Iterable<Graphic<Graphics2D>> sub = Iterables.filter(selection, MOVABLE_PREDICATE);
    if (Iterables.size(sub) < 2) {
        Logger.getLogger(SketchActions.class.getName()).log(Level.INFO,
                "Cannot align with fewer than 2 movable predicates.");
        return;/*from ww  w  . j av  a 2s . c om*/
    }
    ImmutableMap<Graphic<Graphics2D>, Point2D> locs = Maps.toMap(sub, LOC_FUNCTION);
    double yAvg = Points.average(locs.values()).getY();
    for (Graphic<Graphics2D> gr : sub) {
        setPrimitiveLocation((PrimitiveGraphicSupport<?, Graphics2D>) gr,
                new Point2D.Double(locs.get(gr).getX(), yAvg));
    }
}

From source file:com.googlecode.blaisemath.sketch.SketchActions.java

public static void alignVertical(Set<Graphic<Graphics2D>> selection) {
    Iterable<Graphic<Graphics2D>> sub = Iterables.filter(selection, MOVABLE_PREDICATE);
    if (Iterables.size(sub) < 2) {
        Logger.getLogger(SketchActions.class.getName()).log(Level.INFO,
                "Cannot align with fewer than 2 movable predicates.");
        return;//from   w  w w  . j  ava 2s. co m
    }
    ImmutableMap<Graphic<Graphics2D>, Point2D> locs = Maps.toMap(sub, LOC_FUNCTION);
    double xAvg = Points.average(locs.values()).getY();
    for (Graphic<Graphics2D> gr : sub) {
        setPrimitiveLocation((PrimitiveGraphicSupport<?, Graphics2D>) gr,
                new Point2D.Double(xAvg, locs.get(gr).getY()));
    }
}

From source file:com.google.cloud.dataflow.sdk.util.AvroUtils.java

private static Object convertRequiredField(Type avroType, TableFieldSchema fieldSchema, Object v) {
    // REQUIRED fields are represented as the corresponding Avro types. For example, a BigQuery
    // INTEGER type maps to an Avro LONG type.
    checkNotNull(v, "REQUIRED field %s should not be null", fieldSchema.getName());
    ImmutableMap<String, Type> fieldMap = ImmutableMap.<String, Type>builder().put("STRING", Type.STRING)
            .put("BYTES", Type.BYTES).put("INTEGER", Type.LONG).put("FLOAT", Type.DOUBLE)
            .put("BOOLEAN", Type.BOOLEAN).put("TIMESTAMP", Type.LONG).put("RECORD", Type.RECORD)
            .put("DATE", Type.STRING).put("DATETIME", Type.STRING).put("TIME", Type.STRING).build();
    // Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the type field
    // is required, so it may not be null.
    String bqType = fieldSchema.getType();
    Type expectedAvroType = fieldMap.get(bqType);
    verifyNotNull(expectedAvroType, "Unsupported BigQuery type: %s", bqType);
    verify(avroType == expectedAvroType, "Expected Avro schema type %s, not %s, for BigQuery %s field %s",
            expectedAvroType, avroType, bqType, fieldSchema.getName());
    switch (fieldSchema.getType()) {
    case "STRING":
    case "DATE":
    case "DATETIME":
    case "TIME":
        // Avro will use a CharSequence to represent String objects, but it may not always use
        // java.lang.String; for example, it may prefer org.apache.avro.util.Utf8.
        verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass());
        return v.toString();
    case "INTEGER":
        verify(v instanceof Long, "Expected Long, got %s", v.getClass());
        return ((Long) v).toString();
    case "FLOAT":
        verify(v instanceof Double, "Expected Double, got %s", v.getClass());
        return v;
    case "BOOLEAN":
        verify(v instanceof Boolean, "Expected Boolean, got %s", v.getClass());
        return v;
    case "TIMESTAMP":
        // TIMESTAMP data types are represented as Avro LONG types. They are converted back to
        // Strings with variable-precision (up to six digits) to match the JSON files export
        // by BigQuery.
        verify(v instanceof Long, "Expected Long, got %s", v.getClass());
        Double doubleValue = ((Long) v) / 1000000.0;
        return formatTimestamp(doubleValue.toString());
    case "RECORD":
        verify(v instanceof GenericRecord, "Expected GenericRecord, got %s", v.getClass());
        return convertGenericRecordToTableRow((GenericRecord) v, fieldSchema.getFields());
    case "BYTES":
        verify(v instanceof ByteBuffer, "Expected ByteBuffer, got %s", v.getClass());
        ByteBuffer byteBuffer = (ByteBuffer) v;
        byte[] bytes = new byte[byteBuffer.limit()];
        byteBuffer.get(bytes);//from  ww  w.j  a  va  2 s. c om
        return BaseEncoding.base64().encode(bytes);
    default:
        throw new UnsupportedOperationException(
                String.format("Unexpected BigQuery field schema type %s for field named %s",
                        fieldSchema.getType(), fieldSchema.getName()));
    }
}

From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputHelper.java

private static StorageTypeSetter createStorageTypeSetter() {
    final Method setStorageTypeMethod;
    try {/*from  w ww.  ja v a 2s  . c  o m*/
        setStorageTypeMethod = OpWriteBlockProto.Builder.class.getMethod("setStorageType",
                StorageTypeProto.class);
    } catch (NoSuchMethodException e) {
        LOG.warn("noSetStorageType method found, should be hadoop 2.5-", e);
        return new StorageTypeSetter() {

            @Override
            public Builder set(Builder builder, Enum<?> storageType) {
                return builder;
            }
        };
    }
    ImmutableMap.Builder<String, StorageTypeProto> builder = ImmutableMap.builder();
    for (StorageTypeProto storageTypeProto : StorageTypeProto.values()) {
        builder.put(storageTypeProto.name(), storageTypeProto);
    }
    final ImmutableMap<String, StorageTypeProto> name2ProtoEnum = builder.build();
    return new StorageTypeSetter() {

        @Override
        public Builder set(Builder builder, Enum<?> storageType) {
            Object protoEnum = name2ProtoEnum.get(storageType.name());
            try {
                setStorageTypeMethod.invoke(builder, protoEnum);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            return builder;
        }
    };
}

From source file:dollar.api.types.DollarFactory.java

@Nullable
private static Object mapToJsonInternal(@NotNull Value value) {
    final JsonObject json = new JsonObject();
    ImmutableMap<Value, Value> map = value.toVarMap();
    final Set<Value> fieldNames = map.keySet();
    for (Value fieldName : fieldNames) {
        Value v = map.get(fieldName);
        json.putValue(fieldName.toString(), toJson(v));
    }//  w ww .j a v  a2 s .  c om
    return json;
}