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.telefonica.iot.cygnus.management.StatsHandlers.java

/**
 * Handles GET /v1/stats./*from ww  w  .  j  av  a2 s .c  o m*/
 * @param response
 * @param sources
 * @param channels
 * @param sinks
 * @throws IOException
 */
public static void get(HttpServletResponse response, ImmutableMap<String, SourceRunner> sources,
        ImmutableMap<String, Channel> channels, ImmutableMap<String, SinkRunner> sinks) throws IOException {
    response.setContentType("application/json; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    String jsonStr = "{\"success\":\"true\",\"stats\":{\"sources\":[";
    boolean first = true;

    for (String key : sources.keySet()) {
        if (first) {
            first = false;
        } else {
            jsonStr += ",";
        } // if else

        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

        jsonStr += "{\"name\":\"" + source.getName() + "\"," + "\"status\":\""
                + source.getLifecycleState().toString() + "\",";

        if (handler instanceof CygnusHandler) {
            CygnusHandler ch = (CygnusHandler) handler;
            jsonStr += "\"setup_time\":\"" + CommonUtils.getHumanReadable(ch.getBootTime(), true) + "\","
                    + "\"num_received_events\":" + ch.getNumReceivedEvents() + "," + "\"num_processed_events\":"
                    + ch.getNumProcessedEvents() + "}";
        } else {
            jsonStr += "\"setup_time\":\"unknown\"," + "\"num_received_events\":-1,"
                    + "\"num_processed_events\":-1}";
        } // if else
    } // for

    jsonStr += "],\"channels\":[";
    first = true;

    for (String key : channels.keySet()) {
        if (first) {
            first = false;
        } else {
            jsonStr += ",";
        } // if else

        Channel channel = channels.get(key);
        jsonStr += "{\"name\":\"" + channel.getName() + "\"," + "\"status\":\""
                + channel.getLifecycleState().toString() + "\",";

        if (channel instanceof CygnusChannel) {
            CygnusChannel cc = (CygnusChannel) channel;
            jsonStr += "\"setup_time\":\"" + CommonUtils.getHumanReadable(cc.getSetupTime(), true) + "\","
                    + "\"num_events\":" + cc.getNumEvents() + "," + "\"num_puts_ok\":" + cc.getNumPutsOK() + ","
                    + "\"num_puts_failed\":" + cc.getNumPutsFail() + "," + "\"num_takes_ok\":"
                    + cc.getNumTakesOK() + "," + "\"num_takes_failed\":" + cc.getNumTakesFail() + "}";
        } else {
            jsonStr += "\"setup_time\":\"unknown\"," + "\"num_events\":-1," + "\"num_puts_ok\":-1,"
                    + "\"num_puts_failed\":-1," + "\"num_takes_ok\":-1," + "\"num_takes_failed\":-1}";
        } // if else
    } // for

    jsonStr += "],\"sinks\":[";
    first = true;

    for (String key : sinks.keySet()) {
        if (first) {
            first = false;
        } else {
            jsonStr += ",";
        } // if else

        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

        jsonStr += "{\"name\":\"" + sink.getName() + "\"," + "\"status\":\""
                + sink.getLifecycleState().toString() + "\",";

        if (sink instanceof CygnusSink) {
            CygnusSink cs = (CygnusSink) sink;
            jsonStr += "\"setup_time\":\"" + CommonUtils.getHumanReadable(cs.getSetupTime(), true) + "\","
                    + "\"num_processed_events\":" + cs.getNumProcessedEvents() + ","
                    + "\"num_persisted_events\":" + cs.getNumPersistedEvents() + "}";
        } else {
            jsonStr += "\"setup_time\":\"unknown\"," + "\"num_processed_events\":-1,"
                    + "\"num_persisted_events\":-1}";
        } // if else
    } // for

    jsonStr += "]}}";
    response.getWriter().println(jsonStr);
}

From source file:org.apache.rya.kafka.connect.client.CLIDriver.java

private static String makeUsage(final ImmutableMap<String, RyaKafkaClientCommand> commands) {
    final StringBuilder usage = new StringBuilder();
    usage.append("Usage: ").append(CLIDriver.class.getSimpleName()).append(" <command> (<argument> ... )\n");
    usage.append("\n");
    usage.append("Possible Commands:\n");

    // Sort and find the max width of the commands.
    final List<String> sortedCommandNames = Lists.newArrayList(commands.keySet());
    Collections.sort(sortedCommandNames);

    int maxCommandLength = 0;
    for (final String commandName : sortedCommandNames) {
        maxCommandLength = commandName.length() > maxCommandLength ? commandName.length() : maxCommandLength;
    }//w ww. j a  v a2s  . c om

    // Add each command to the usage.
    final String commandFormat = "    %-" + maxCommandLength + "s - %s\n";
    for (final String commandName : sortedCommandNames) {
        final String commandDescription = commands.get(commandName).getDescription();
        usage.append(String.format(commandFormat, commandName, commandDescription));
    }

    return usage.toString();
}

From source file:dagger.internal.codegen.ProducerFactoryGenerator.java

private static ImmutableList<CodeBlock> getParameterCodeBlocks(ProductionBinding binding,
        ImmutableMap<BindingKey, FieldSpec> fields, String listArgName) {
    int argIndex = 0;
    ImmutableList.Builder<CodeBlock> codeBlocks = ImmutableList.builder();
    for (DependencyRequest dependency : binding.explicitDependencies()) {
        if (isAsyncDependency(dependency)) {
            codeBlocks.add(//  w  ww.java  2  s  . com
                    CodeBlock.of("($T) $L.get($L)", asyncDependencyType(dependency), listArgName, argIndex));
            argIndex++;
        } else {
            codeBlocks.add(frameworkTypeUsageStatement(CodeBlock.of("$N", fields.get(dependency.bindingKey())),
                    dependency.kind()));
        }
    }
    return codeBlocks.build();
}

From source file:org.apache.rya.streams.client.CLIDriver.java

private static String makeUsage(final ImmutableMap<String, RyaStreamsCommand> commands) {
    final StringBuilder usage = new StringBuilder();
    usage.append("Usage: ").append(CLIDriver.class.getSimpleName()).append(" <command> (<argument> ... )\n");
    usage.append("\n");
    usage.append("Possible Commands:\n");

    // Sort and find the max width of the commands.
    final List<String> sortedCommandNames = Lists.newArrayList(commands.keySet());
    Collections.sort(sortedCommandNames);

    int maxCommandLength = 0;
    for (final String commandName : sortedCommandNames) {
        maxCommandLength = commandName.length() > maxCommandLength ? commandName.length() : maxCommandLength;
    }/*from  w  w  w. j av  a2s .co m*/

    // Add each command to the usage.
    final String commandFormat = "    %-" + maxCommandLength + "s - %s\n";
    for (final String commandName : sortedCommandNames) {
        final String commandDescription = commands.get(commandName).getDescription();
        usage.append(String.format(commandFormat, commandName, commandDescription));
    }

    return usage.toString();
}

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

/**
 * Create a cell provider at a given root.
 *//*from w ww  .jav  a  2s.  c o m*/
public static CellProvider createForLocalBuild(ProjectFilesystem rootFilesystem, Watchman watchman,
        BuckConfig rootConfig, CellConfig rootCellConfigOverrides,
        KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) throws IOException {

    DefaultCellPathResolver rootCellCellPathResolver = DefaultCellPathResolver
            .createWithConfigRepositoriesSection(rootFilesystem.getRootPath(),
                    rootConfig.getEntriesForSection(DefaultCellPathResolver.REPOSITORIES_SECTION));

    ImmutableMap<RelativeCellName, Path> transitiveCellPathMapping = rootCellCellPathResolver
            .getTransitivePathMapping();

    ImmutableMap<Path, RawConfig> pathToConfigOverrides;
    try {
        pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(transitiveCellPathMapping);
    } catch (CellConfig.MalformedOverridesException e) {
        throw new HumanReadableException(e.getMessage());
    }

    ImmutableSet<Path> allRoots = ImmutableSet.copyOf(transitiveCellPathMapping.values());
    return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() {
        @Override
        public Cell load(Path cellPath) throws IOException, InterruptedException {
            cellPath = cellPath.toRealPath().normalize();

            Preconditions.checkState(allRoots.contains(cellPath),
                    "Cell %s outside of transitive closure of root cell (%s).", cellPath, allRoots);

            RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(cellPath))
                    .orElse(RawConfig.of(ImmutableMap.of()));
            Config config = Configs.createDefaultConfig(cellPath, configOverrides);
            DefaultCellPathResolver cellPathResolver = new DefaultCellPathResolver(cellPath, config);
            ProjectFilesystem cellFilesystem = new ProjectFilesystem(cellPath, config);

            BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(),
                    rootConfig.getPlatform(), rootConfig.getEnvironment(), cellPathResolver);

            // TODO(13777679): cells in other watchman roots do not work correctly.

            return new Cell(cellPathResolver.getKnownRoots(), cellFilesystem, watchman, buckConfig,
                    knownBuildRuleTypesFactory, cellProvider);
        }
    }, cellProvider -> {
        try {
            return new Cell(rootCellCellPathResolver.getKnownRoots(), rootFilesystem, watchman, rootConfig,
                    knownBuildRuleTypesFactory, cellProvider);
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while loading root cell", e);
        } catch (IOException e) {
            throw new HumanReadableException("Failed to load root cell", e);
        }
    });
}

From source file:com.siemens.sw360.importer.ComponentImportUtils.java

@Nullable
private static List<AttachmentContent> getAttachmentContents(
        HashMap<String, List<String>> releaseIdentifierToDownloadURL,
        ImmutableMap<String, AttachmentContent> URLtoAttachment, String releaseIdentifier) {
    List<AttachmentContent> attachmentContents = null;
    if (releaseIdentifierToDownloadURL.containsKey(releaseIdentifier)) {

        final List<String> URLs = releaseIdentifierToDownloadURL.get(releaseIdentifier);
        attachmentContents = new ArrayList<>(URLs.size());
        for (String url : URLs) {
            if (URLtoAttachment.containsKey(url)) {
                final AttachmentContent attachmentContent = URLtoAttachment.get(url);
                attachmentContents.add(attachmentContent);
            }//  w w w.j  a  v  a2s . c  om
        }
    }
    return attachmentContents;
}

From source file:com.facebook.buck.core.cell.impl.LocalCellProviderFactory.java

/** Create a cell provider at a given root. */
public static CellProvider create(ProjectFilesystem rootFilesystem, BuckConfig rootConfig,
        CellConfig rootCellConfigOverrides, ImmutableMap<CellName, Path> cellPathMapping,
        CellPathResolver rootCellCellPathResolver, BuckModuleManager moduleManager,
        ToolchainProviderFactory toolchainProviderFactory, ProjectFilesystemFactory projectFilesystemFactory,
        UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) {

    ImmutableMap<Path, RawConfig> pathToConfigOverrides;
    try {//from   ww w .j a va 2 s.c o m
        pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(cellPathMapping);
    } catch (InvalidCellOverrideException e) {
        throw new HumanReadableException(e.getMessage());
    }

    ImmutableSet<Path> allRoots = ImmutableSet.copyOf(cellPathMapping.values());
    return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() {
        @Override
        public Cell load(Path cellPath) throws IOException, InterruptedException {
            Path normalizedCellPath = cellPath.toRealPath().normalize();

            Preconditions.checkState(allRoots.contains(normalizedCellPath),
                    "Cell %s outside of transitive closure of root cell (%s).", normalizedCellPath, allRoots);

            RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(normalizedCellPath))
                    .orElse(RawConfig.of(ImmutableMap.of()));
            Config config = Configs.createDefaultConfig(normalizedCellPath, configOverrides);

            ImmutableMap<String, Path> cellMapping = DefaultCellPathResolver
                    .getCellPathsFromConfigRepositoriesSection(cellPath,
                            config.get(DefaultCellPathResolver.REPOSITORIES_SECTION));

            // The cell should only contain a subset of cell mappings of the root cell.
            cellMapping.forEach((name, path) -> {
                Path pathInRootResolver = rootCellCellPathResolver.getCellPaths().get(name);
                if (pathInRootResolver == null) {
                    throw new HumanReadableException(
                            "In the config of %s:  %s.%s must exist in the root cell's cell mappings.",
                            cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name);
                } else if (!pathInRootResolver.equals(path)) {
                    throw new HumanReadableException(
                            "In the config of %s:  %s.%s must point to the same directory as the root "
                                    + "cell's cell mapping: (root) %s != (current) %s",
                            cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name,
                            pathInRootResolver, path);
                }
            });

            CellPathResolver cellPathResolver = new CellPathResolverView(rootCellCellPathResolver,
                    cellMapping.keySet(), cellPath);

            Optional<EmbeddedCellBuckOutInfo> embeddedCellBuckOutInfo = Optional.empty();
            Optional<String> canonicalCellName = cellPathResolver.getCanonicalCellName(normalizedCellPath);
            if (rootConfig.getView(BuildBuckConfig.class).isEmbeddedCellBuckOutEnabled()
                    && canonicalCellName.isPresent()) {
                embeddedCellBuckOutInfo = Optional
                        .of(EmbeddedCellBuckOutInfo.of(rootFilesystem.resolve(rootFilesystem.getRootPath()),
                                rootFilesystem.getBuckPaths(), canonicalCellName.get()));
            }
            ProjectFilesystem cellFilesystem = projectFilesystemFactory
                    .createProjectFilesystem(normalizedCellPath, config, embeddedCellBuckOutInfo);

            BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(),
                    rootConfig.getPlatform(), rootConfig.getEnvironment(),
                    buildTargetName -> unconfiguredBuildTargetFactory.create(cellPathResolver,
                            buildTargetName));

            RuleKeyConfiguration ruleKeyConfiguration = ConfigRuleKeyConfigurationFactory.create(buckConfig,
                    moduleManager);

            ToolchainProvider toolchainProvider = toolchainProviderFactory.create(buckConfig, cellFilesystem,
                    ruleKeyConfiguration);

            // TODO(13777679): cells in other watchman roots do not work correctly.

            return ImmutableCell.of(cellPathResolver.getKnownRoots(), canonicalCellName, cellFilesystem,
                    buckConfig, cellProvider, toolchainProvider, ruleKeyConfiguration, cellPathResolver);
        }
    }, cellProvider -> RootCellFactory.create(cellProvider, rootCellCellPathResolver, toolchainProviderFactory,
            rootFilesystem, moduleManager, rootConfig));
}

From source file:de.adrodoc55.minecraft.mpl.conversion.SchematicConverter.java

public static TagCompound convert(MplCompilationResult result) {
    ImmutableMap<Coordinate3D, MplBlock> blockMap = result.getBlocks();
    ImmutableSet<Coordinate3D> coordinates = blockMap.keySet();
    Coordinate3D min = getMinCoordinate(coordinates);
    Coordinate3D max = getMaxCoordinate(coordinates);
    short width = (short) (1 + max.getX() - min.getX());
    short heigth = (short) (1 + max.getY() - min.getY());
    short length = (short) (1 + max.getZ() - min.getZ());
    int volume = width * heigth * length;
    ByteBuffer blocks = ByteBuffer.allocate(volume);
    ByteBuffer data = ByteBuffer.allocate(volume);
    List<ITag> tileEntities = new ArrayList<>(blockMap.size());
    for (int y = min.getY(); y <= max.getY(); y++) {
        for (int z = min.getZ(); z <= max.getZ(); z++) {
            for (int x = min.getX(); x <= max.getX(); x++) {
                Coordinate3D coord = new Coordinate3D(x, y, z);
                MplBlock block = blockMap.get(coord);
                if (block == null) {
                    block = new AirBlock(coord);
                }//from ww  w  .  ja v a2s . c o m

                // block
                blocks.put(block.getByteBlockId());

                // data
                if (block instanceof CommandBlock) {
                    data.put(((CommandBlock) block).getDamageValue());
                } else {
                    data.put((byte) 0);
                }

                // tile entity
                if (block instanceof CommandBlock) {
                    tileEntities.add(toControl((CommandBlock) block));
                }
            }
        }
    }
    TagCompound schematic = new TagCompound("Schematic");
    schematic.setTag(new TagShort("Width", width));
    schematic.setTag(new TagShort("Height", heigth));
    schematic.setTag(new TagShort("Length", length));
    schematic.setTag(new TagString("Materials", "Alpha"));
    schematic.setTag(new TagByteArray("Blocks", blocks.array()));
    schematic.setTag(new TagByteArray("Data", data.array()));
    schematic.setTag(new TagList("TileEntities", tileEntities));
    schematic.setTag(new TagList("Entities", new ArrayList<>()));
    schematic.setTag(new TagList("TileTicks", new ArrayList<>()));
    return schematic;
}

From source file:de.metas.ui.web.document.filter.sql.SqlDocumentFilterConverterContext.java

public int getPropertyAsInt(@NonNull final String name, final int defaultValue) {
    final ImmutableMap<String, Object> params = getParams();
    final Object value = params.get(name);
    return NumberUtils.asInt(value, defaultValue);
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

private static StorageTypeSetter createStorageTypeSetter() {
    final Method setStorageTypeMethod;
    try {/*ww w .j  av a  2  s.  c o  m*/
        setStorageTypeMethod = OpWriteBlockProto.Builder.class.getMethod("setStorageType",
                StorageTypeProto.class);
    } catch (NoSuchMethodException e) {
        LOG.debug("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;
        }
    };
}