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.watchman.environment.ExecutableFinder.java

private static ImmutableSet<Path> getPaths(ImmutableMap<String, String> env) {
    ImmutableSet.Builder<Path> paths = ImmutableSet.builder();

    // Add the empty path so that when we iterate over it, we can check for the suffixed version of
    // a given path, be it absolute or not.
    paths.add(Paths.get(""));

    String pathEnv = env.get("PATH");
    if (pathEnv != null) {
        paths.addAll(FluentIterable.from(Splitter.on(pathSeparator).omitEmptyStrings().split(pathEnv))
                .transform(TO_PATH));/*from w  ww . j  a  v a 2s. co  m*/
    }

    if (Platform.isMac()) {
        Path osXPaths = Paths.get("/etc/paths");
        if (Files.exists(osXPaths)) {
            try {
                paths.addAll(FluentIterable.from(Files.readAllLines(osXPaths, Charset.defaultCharset()))
                        .transform(TO_PATH));
            } catch (IOException e) {
            }
        }
    }

    return paths.build();
}

From source file:org.apache.cassandra.hints.HintsDescriptor.java

/**
 * Create, if necessary, the required encryption components (for either decrpyt or encrypt operations).
 * Note that in the case of encyption (this is, when writing out a new hints file), we need to write
 * the cipher's IV out to the header so it can be used when decrypting. Thus, we need to add an additional
 * entry to the {@code params} map./*from w w  w.  ja va2  s  .  c  o m*/
 *
 * @param params the base parameters into the descriptor.
 * @return null if not using encryption; else, the initialized {@link Cipher} and a possibly updated version
 * of the {@code params} map.
 */
@SuppressWarnings("unchecked")
static EncryptionData createEncryption(ImmutableMap<String, Object> params) {
    if (params.containsKey(ENCRYPTION)) {
        Map<?, ?> encryptionConfig = (Map<?, ?>) params.get(ENCRYPTION);
        EncryptionContext encryptionContext = EncryptionContext.createFromMap(encryptionConfig,
                DatabaseDescriptor.getEncryptionContext());

        try {
            Cipher cipher;
            if (encryptionConfig.containsKey(EncryptionContext.ENCRYPTION_IV)) {
                cipher = encryptionContext.getDecryptor();
            } else {
                cipher = encryptionContext.getEncryptor();
                ImmutableMap<String, Object> encParams = ImmutableMap.<String, Object>builder()
                        .putAll(encryptionContext.toHeaderParameters())
                        .put(EncryptionContext.ENCRYPTION_IV, Hex.bytesToHex(cipher.getIV())).build();

                Map<String, Object> map = new HashMap<>(params);
                map.put(ENCRYPTION, encParams);
                params = ImmutableMap.<String, Object>builder().putAll(map).build();
            }
            return new EncryptionData(cipher, encryptionContext.getCompressor(), params);
        } catch (IOException ioe) {
            logger.warn("failed to create encyption context for hints file. ignoring encryption for hints.",
                    ioe);
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.spectralogic.ds3autogen.converters.ResponseTypeConverter.java

/**
 * Retrieves the annotation name (i.e. "Value") that should be used for
 * proper xml parsing of model created by this Encapsulating Type Names
 * object./*from   ww w  .  j a v a 2  s.  c  o  m*/
 */
protected static String getAnnotationName(final EncapsulatingTypeNames encapsulatingType,
        final ImmutableMap<String, Ds3Type> typeMap) {
    if (hasNoRootElement(encapsulatingType)) {
        return "Tape";
    }
    if (hasContent(typeMap)) {
        final Ds3Type childType = typeMap.get(encapsulatingType.getSdkName());
        if (childType != null && hasContent(childType.getNameToMarshal())
                && !childType.getNameToMarshal().equals("Data")) {
            return childType.getNameToMarshal();
        }
    }
    if (hasContent(encapsulatingType.getOriginalName())) {
        return encapsulatingType.getOriginalName();
    }
    return stripPath(encapsulatingType.getSdkName());
}

From source file:com.facebook.buck.apple.AppleNativeIntegrationTestUtils.java

public static boolean isSwiftAvailable(ApplePlatform platform) {
    BuckConfig buckConfig = FakeBuckConfig.builder().build();
    ImmutableMap<AppleSdk, AppleSdkPaths> sdkPaths = discoverSystemSdkPaths(buckConfig);
    Optional<AppleSdk> anySdkOptional = anySdkForPlatform(platform, sdkPaths);
    if (!anySdkOptional.isPresent()) {
        return false;
    }/*from   w  ww  .  jav  a 2  s.com*/
    AppleSdk anySdk = anySdkOptional.get();
    AppleCxxPlatform appleCxxPlatform = AppleCxxPlatforms.build(new FakeProjectFilesystem(), anySdk,
            "fakeversion", "fakearch", sdkPaths.get(anySdk), buckConfig, new AppleConfig(buckConfig),
            Optional.of(new DefaultProcessExecutor(Console.createNullConsole())), Optional.empty());
    return appleCxxPlatform.getSwiftPlatform().isPresent();
}

From source file:com.cognifide.aet.runner.conversion.SuiteMergeStrategy.java

/**
 * Merges current and pattern suite. All comments, version and patterns in current suite are overwritten from pattern suite.
 *
 * @param current - current run suite./*from   w  ww  .  j ava 2s  . co  m*/
 * @param pattern - pattern suite, usually the last run.
 * @return merged suite.
 */
public static Suite merge(Suite current, Suite pattern) {
    final ImmutableMap<String, Test> tests = FluentIterable.from(current.getTests()).uniqueIndex(TEST_TO_MAP);

    if (pattern != null) {
        current.setVersion(pattern.getVersion() + 1);
        updateComment(current, pattern);
        for (Test patternTest : pattern.getTests()) {
            if (tests.containsKey(patternTest.getName())) {
                mergeTest(tests.get(patternTest.getName()), patternTest);
            }
        }
    } else {
        current.setVersion(1L);
    }
    return current;
}

From source file:com.facebook.buck.rules.CellProvider.java

public static CellProvider createForDistributedBuild(ImmutableMap<Path, BuckConfig> cellConfigs,
        ImmutableMap<Path, ProjectFilesystem> cellFilesystems,
        KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) {
    return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() {
        @Override//from   w w w.j  av a 2  s. c  om
        public Cell load(Path cellPath) throws Exception {
            ProjectFilesystem cellFilesystem = Preconditions.checkNotNull(cellFilesystems.get(cellPath));
            BuckConfig buckConfig = Preconditions.checkNotNull(cellConfigs.get(cellPath));

            return new Cell(cellConfigs.keySet(), cellFilesystem, Watchman.NULL_WATCHMAN, buckConfig,
                    knownBuildRuleTypesFactory, cellProvider);
        }
    }, null);
}

From source file:com.facebook.buck.apple.AppleSdkDiscovery.java

/**
 * Given a path to an Xcode developer directory and a map of
 * (xctoolchain ID: path) pairs as returned by
 * {@link AppleToolchainDiscovery}, walks through the platforms
 * and builds a map of ({@link AppleSdk}: {@link AppleSdkPaths})
 * objects describing the paths to the SDKs inside.
 *
 * The {@link AppleSdk#getName()} strings match the ones displayed by {@code xcodebuild -showsdks}
 * and look like {@code macosx10.9}, {@code iphoneos8.0}, {@code iphonesimulator8.0},
 * etc./*  w  ww .j a v a  2 s  . c o  m*/
 */
public static ImmutableMap<AppleSdk, AppleSdkPaths> discoverAppleSdkPaths(Optional<Path> developerDir,
        ImmutableList<Path> extraDirs, ImmutableMap<String, AppleToolchain> xcodeToolchains,
        AppleConfig appleConfig) throws IOException {
    Optional<AppleToolchain> defaultToolchain = Optional.ofNullable(xcodeToolchains.get(DEFAULT_TOOLCHAIN_ID));

    ImmutableMap.Builder<AppleSdk, AppleSdkPaths> appleSdkPathsBuilder = ImmutableMap.builder();

    HashSet<Path> platformPaths = new HashSet<Path>(extraDirs);
    if (developerDir.isPresent()) {
        Path platformsDir = developerDir.get().resolve("Platforms");
        LOG.debug("Searching for Xcode platforms under %s", platformsDir);
        platformPaths.add(platformsDir);
    }

    // We need to find the most recent SDK for each platform so we can
    // make the fall-back SDKs with no version number in their name
    // ("macosx", "iphonesimulator", "iphoneos").
    //
    // To do this, we store a map of (platform: [sdk1, sdk2, ...])
    // pairs where the SDKs for each platform are ordered by version.
    TreeMultimap<ApplePlatform, AppleSdk> orderedSdksForPlatform = TreeMultimap.create(Ordering.natural(),
            APPLE_SDK_VERSION_ORDERING);

    for (Path platforms : platformPaths) {
        if (!Files.exists(platforms)) {
            LOG.debug("Skipping platform search path %s that does not exist", platforms);
            continue;
        }
        LOG.debug("Searching for Xcode SDKs in %s", platforms);

        try (DirectoryStream<Path> platformStream = Files.newDirectoryStream(platforms, "*.platform")) {
            for (Path platformDir : platformStream) {
                Path developerSdksPath = platformDir.resolve("Developer/SDKs");
                try (DirectoryStream<Path> sdkStream = Files.newDirectoryStream(developerSdksPath, "*.sdk")) {
                    Set<Path> scannedSdkDirs = new HashSet<>();
                    for (Path sdkDir : sdkStream) {
                        LOG.debug("Fetching SDK name for %s", sdkDir);

                        sdkDir = sdkDir.toRealPath();
                        if (scannedSdkDirs.contains(sdkDir)) {
                            LOG.debug("Skipping already scanned SDK directory %s", sdkDir);
                            continue;
                        }

                        AppleSdk.Builder sdkBuilder = AppleSdk.builder();
                        if (buildSdkFromPath(sdkDir, sdkBuilder, xcodeToolchains, defaultToolchain,
                                appleConfig)) {
                            AppleSdk sdk = sdkBuilder.build();
                            LOG.debug("Found SDK %s", sdk);

                            AppleSdkPaths.Builder xcodePathsBuilder = AppleSdkPaths.builder();
                            for (AppleToolchain toolchain : sdk.getToolchains()) {
                                xcodePathsBuilder.addToolchainPaths(toolchain.getPath());
                            }
                            AppleSdkPaths xcodePaths = xcodePathsBuilder.setDeveloperPath(developerDir)
                                    .setPlatformPath(platformDir).setSdkPath(sdkDir).build();
                            appleSdkPathsBuilder.put(sdk, xcodePaths);
                            orderedSdksForPlatform.put(sdk.getApplePlatform(), sdk);
                        }
                        scannedSdkDirs.add(sdkDir);
                    }
                } catch (NoSuchFileException e) {
                    LOG.warn(e, "Couldn't discover SDKs at path %s, ignoring platform %s", developerSdksPath,
                            platformDir);
                }
            }
        }
    }

    // Get a snapshot of what's in appleSdkPathsBuilder, then for each
    // ApplePlatform, add to appleSdkPathsBuilder the most recent
    // SDK with an unversioned name.
    ImmutableMap<AppleSdk, AppleSdkPaths> discoveredSdkPaths = appleSdkPathsBuilder.build();

    for (ApplePlatform platform : orderedSdksForPlatform.keySet()) {
        Set<AppleSdk> platformSdks = orderedSdksForPlatform.get(platform);
        boolean shouldCreateUnversionedSdk = true;
        for (AppleSdk sdk : platformSdks) {
            shouldCreateUnversionedSdk &= !sdk.getName().equals(platform.getName());
        }

        if (shouldCreateUnversionedSdk) {
            AppleSdk mostRecentSdkForPlatform = orderedSdksForPlatform.get(platform).last();
            appleSdkPathsBuilder.put(mostRecentSdkForPlatform.withName(platform.getName()),
                    discoveredSdkPaths.get(mostRecentSdkForPlatform));
        }
    }

    // This includes both the discovered SDKs with versions in their names, as well as
    // the unversioned aliases added just above.
    return appleSdkPathsBuilder.build();
}

From source file:com.google.testing.junit.runner.internal.StackTraces.java

/**
 * Prints all stack traces to the given stream.
 *
 * @param out Stream to print to//ww  w .  j  ava2  s.  com
 */
public static void printAll(PrintStream out) {
    out.println("Starting full thread dump ...\n");
    ThreadMXBean mb = ManagementFactory.getThreadMXBean();

    // ThreadInfo has comprehensive information such as locks.
    ThreadInfo[] threadInfos = mb.dumpAllThreads(true, true);

    // But we can know whether a thread is daemon only from Thread
    Set<Thread> threads = Thread.getAllStackTraces().keySet();
    ImmutableMap<Long, Thread> threadMap = Maps.uniqueIndex(threads, new Function<Thread, Long>() {
        @Override
        public Long apply(Thread thread) {
            return thread.getId();
        }
    });

    // Dump non-daemon threads first
    for (ThreadInfo threadInfo : threadInfos) {
        Thread thread = threadMap.get(threadInfo.getThreadId());
        if (thread != null && !thread.isDaemon()) {
            dumpThreadInfo(threadInfo, thread, out);
        }
    }

    // Dump daemon threads
    for (ThreadInfo threadInfo : threadInfos) {
        Thread thread = threadMap.get(threadInfo.getThreadId());
        if (thread != null && thread.isDaemon()) {
            dumpThreadInfo(threadInfo, thread, out);
        }
    }

    long[] deadlockedThreads = mb.findDeadlockedThreads();
    if (deadlockedThreads != null) {
        out.println("Detected deadlocked threads: " + Arrays.toString(deadlockedThreads));
    }
    long[] monitorDeadlockedThreads = mb.findMonitorDeadlockedThreads();
    if (monitorDeadlockedThreads != null) {
        out.println("Detected monitor deadlocked threads: " + Arrays.toString(monitorDeadlockedThreads));
    }
    out.println("\nDone full thread dump.");
    out.flush();
}

From source file:com.facebook.buck.apple.toolchain.impl.AppleSdkDiscovery.java

/**
 * Given a path to an Xcode developer directory and a map of (xctoolchain ID: path) pairs as
 * returned by {@link AppleToolchainDiscovery}, walks through the platforms and builds a map of
 * ({@link AppleSdk}: {@link AppleSdkPaths}) objects describing the paths to the SDKs inside.
 *
 * <p>The {@link AppleSdk#getName()} strings match the ones displayed by {@code xcodebuild
 * -showsdks} and look like {@code macosx10.9}, {@code iphoneos8.0}, {@code iphonesimulator8.0},
 * etc.//w  w  w. java2s .  c o  m
 */
public static ImmutableMap<AppleSdk, AppleSdkPaths> discoverAppleSdkPaths(Optional<Path> developerDir,
        ImmutableList<Path> extraDirs, ImmutableMap<String, AppleToolchain> xcodeToolchains,
        AppleConfig appleConfig) throws IOException {
    Optional<AppleToolchain> defaultToolchain = Optional.ofNullable(xcodeToolchains.get(DEFAULT_TOOLCHAIN_ID));

    ImmutableMap.Builder<AppleSdk, AppleSdkPaths> appleSdkPathsBuilder = ImmutableMap.builder();

    HashSet<Path> platformPaths = new HashSet<Path>(extraDirs);
    if (developerDir.isPresent()) {
        Path platformsDir = developerDir.get().resolve("Platforms");
        LOG.debug("Searching for Xcode platforms under %s", platformsDir);
        platformPaths.add(platformsDir);
    }

    // We need to find the most recent SDK for each platform so we can
    // make the fall-back SDKs with no version number in their name
    // ("macosx", "iphonesimulator", "iphoneos").
    //
    // To do this, we store a map of (platform: [sdk1, sdk2, ...])
    // pairs where the SDKs for each platform are ordered by version.
    TreeMultimap<ApplePlatform, AppleSdk> orderedSdksForPlatform = TreeMultimap.create(Ordering.natural(),
            APPLE_SDK_VERSION_ORDERING);

    for (Path platforms : platformPaths) {
        if (!Files.exists(platforms)) {
            LOG.debug("Skipping platform search path %s that does not exist", platforms);
            continue;
        }
        LOG.debug("Searching for Xcode SDKs in %s", platforms);

        try (DirectoryStream<Path> platformStream = Files.newDirectoryStream(platforms, "*.platform")) {
            for (Path platformDir : platformStream) {
                Path developerSdksPath = platformDir.resolve("Developer/SDKs");
                try (DirectoryStream<Path> sdkStream = Files.newDirectoryStream(developerSdksPath, "*.sdk")) {
                    Set<Path> scannedSdkDirs = new HashSet<>();
                    for (Path sdkDir : sdkStream) {
                        LOG.debug("Fetching SDK name for %s", sdkDir);

                        try {
                            sdkDir = sdkDir.toRealPath();
                        } catch (NoSuchFileException e) {
                            LOG.warn(e, "SDK at path %s is a dangling link, ignoring", sdkDir);
                            continue;
                        }
                        if (scannedSdkDirs.contains(sdkDir)) {
                            LOG.debug("Skipping already scanned SDK directory %s", sdkDir);
                            continue;
                        }

                        AppleSdk.Builder sdkBuilder = AppleSdk.builder();
                        if (buildSdkFromPath(sdkDir, sdkBuilder, xcodeToolchains, defaultToolchain,
                                appleConfig)) {
                            AppleSdk sdk = sdkBuilder.build();
                            LOG.debug("Found SDK %s", sdk);

                            AppleSdkPaths.Builder xcodePathsBuilder = AppleSdkPaths.builder();
                            for (AppleToolchain toolchain : sdk.getToolchains()) {
                                xcodePathsBuilder.addToolchainPaths(toolchain.getPath());
                            }
                            AppleSdkPaths xcodePaths = xcodePathsBuilder.setDeveloperPath(developerDir)
                                    .setPlatformPath(platformDir).setSdkPath(sdkDir).build();
                            appleSdkPathsBuilder.put(sdk, xcodePaths);
                            orderedSdksForPlatform.put(sdk.getApplePlatform(), sdk);
                        }
                        scannedSdkDirs.add(sdkDir);
                    }
                } catch (NoSuchFileException e) {
                    LOG.warn(e, "Couldn't discover SDKs at path %s, ignoring platform %s", developerSdksPath,
                            platformDir);
                }
            }
        }
    }

    // Get a snapshot of what's in appleSdkPathsBuilder, then for each
    // ApplePlatform, add to appleSdkPathsBuilder the most recent
    // SDK with an unversioned name.
    ImmutableMap<AppleSdk, AppleSdkPaths> discoveredSdkPaths = appleSdkPathsBuilder.build();

    for (ApplePlatform platform : orderedSdksForPlatform.keySet()) {
        Set<AppleSdk> platformSdks = orderedSdksForPlatform.get(platform);
        boolean shouldCreateUnversionedSdk = true;
        for (AppleSdk sdk : platformSdks) {
            shouldCreateUnversionedSdk &= !sdk.getName().equals(platform.getName());
        }

        if (shouldCreateUnversionedSdk) {
            AppleSdk mostRecentSdkForPlatform = orderedSdksForPlatform.get(platform).last();
            appleSdkPathsBuilder.put(mostRecentSdkForPlatform.withName(platform.getName()),
                    discoveredSdkPaths.get(mostRecentSdkForPlatform));
        }
    }

    // This includes both the discovered SDKs with versions in their names, as well as
    // the unversioned aliases added just above.
    return appleSdkPathsBuilder.build();
}

From source file:org.jetbrains.kotlin.codegen.RangeCodegenUtil.java

@Nullable
private static PrimitiveType getPrimitiveRangeOrProgressionElementType(@NotNull KotlinType rangeOrProgression,
        @NotNull ImmutableMap<FqName, PrimitiveType> map) {
    ClassifierDescriptor declarationDescriptor = rangeOrProgression.getConstructor().getDeclarationDescriptor();
    if (declarationDescriptor == null)
        return null;
    FqNameUnsafe fqName = DescriptorUtils.getFqName(declarationDescriptor);
    if (!fqName.isSafe())
        return null;
    return map.get(fqName.toSafe());
}