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

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

Introduction

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

Prototype

public ImmutableSet<K> keySet() 

Source Link

Usage

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  w w.ja va  2  s  . c  o  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:eu.trentorise.opendata.semtext.SemTexts.java

/**
 * Returns a copy of provided metadata with {@code newMetadata} set under
 * the given namespace./*from  w  w  w.j  a  v a  2s  .  c om*/
 *
 * @param newMetadata Must be an immutable object.
 */
static ImmutableMap<String, ?> replaceMetadata(ImmutableMap<String, ?> metadata, String namespace,
        Object newMetadata) {
    ImmutableMap.Builder<String, Object> mapb = ImmutableMap.builder();
    for (String ns : metadata.keySet()) {
        if (!ns.equals(namespace)) {
            mapb.put(ns, metadata.get(ns));
        }
    }
    mapb.put(namespace, newMetadata);
    return mapb.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  a  v a  2s. c o  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.core.cell.impl.DefaultCellPathResolver.java

/**
 * Helper function to precompute the {@link CellName} to Path mapping
 *
 * @return Map of cell name to path.//from  w  ww.  j  a  v a 2 s  . c  om
 */
private static ImmutableMap<CellName, Path> bootstrapPathMapping(Path root,
        ImmutableMap<String, Path> cellPaths) {
    ImmutableMap.Builder<CellName, Path> builder = ImmutableMap.builder();
    // Add the implicit empty root cell
    builder.put(CellName.ROOT_CELL_NAME, root);
    HashSet<Path> seenPaths = new HashSet<>();

    ImmutableSortedSet<String> sortedCellNames = ImmutableSortedSet.<String>naturalOrder()
            .addAll(cellPaths.keySet()).build();
    for (String cellName : sortedCellNames) {
        Path cellRoot = Objects.requireNonNull(cellPaths.get(cellName),
                "cellName is derived from the map, get() should always return a value.");
        try {
            cellRoot = cellRoot.toRealPath().normalize();
        } catch (IOException e) {
            LOG.warn("cellroot [" + cellRoot + "] does not exist in filesystem");
        }
        if (seenPaths.contains(cellRoot)) {
            continue;
        }
        builder.put(CellName.of(cellName), cellRoot);
        seenPaths.add(cellRoot);
    }
    return builder.build();
}

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

/**
 * Handles PUT /v1/stats (reset)./*from  www.j  a va  2 s  . co  m*/
 * @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:com.facebook.buck.apple.CompilationDatabase.java

static AppleSdkPaths selectNewestSimulatorSdk(ImmutableMap<String, AppleSdkPaths> allAppleSdkPaths) {
    final String prefix = "iphonesimulator";
    List<String> iphoneSimulatorVersions = Lists
            .newArrayList(FluentIterable.from(allAppleSdkPaths.keySet()).filter(new Predicate<String>() {
                @Override/*from  ww  w  . ja  v a  2 s.c o m*/
                public boolean apply(String sdkName) {
                    return sdkName.startsWith(prefix);
                }
            }).transform(new Function<String, String>() {
                @Override
                public String apply(String sdkName) {
                    return sdkName.substring(prefix.length());
                }
            }).toSet());
    if (iphoneSimulatorVersions.isEmpty()) {
        throw new RuntimeException("No iphonesimulator found in: " + allAppleSdkPaths.keySet());
    }

    Collections.sort(iphoneSimulatorVersions, new VersionStringComparator());
    String version = iphoneSimulatorVersions.get(iphoneSimulatorVersions.size() - 1);
    return Preconditions.checkNotNull(allAppleSdkPaths.get(prefix + version));
}

From source file:com.facebook.buck.features.python.PythonBinaryDescription.java

public static ImmutableMap<Path, SourcePath> addMissingInitModules(ImmutableMap<Path, SourcePath> modules,
        SourcePath emptyInit) {//from   w  w  w  . j  av a2  s  . co m

    Map<Path, SourcePath> initModules = new LinkedHashMap<>();

    // Insert missing `__init__.py` modules.
    Set<Path> packages = new HashSet<>();
    for (Path module : modules.keySet()) {
        Path pkg = module;
        while ((pkg = pkg.getParent()) != null && !packages.contains(pkg)) {
            Path init = pkg.resolve("__init__.py");
            if (!modules.containsKey(init)) {
                initModules.put(init, emptyInit);
            }
            packages.add(pkg);
        }
    }

    return ImmutableMap.<Path, SourcePath>builder().putAll(modules).putAll(initModules).build();
}

From source file:google.registry.model.registry.label.PremiumListUtils.java

/**
 * Persists a new or updated PremiumList object and its descendant entities to Datastore.
 *
 * <p>The flow here is: save the new premium list entries parented on that revision entity,
 * save/update the PremiumList, and then delete the old premium list entries associated with the
 * old revision./*w  ww.j  av a  2 s  .co m*/
 *
 * <p>This is the only valid way to save these kinds of entities!
 */
public static PremiumList savePremiumListAndEntries(final PremiumList premiumList,
        ImmutableMap<String, PremiumListEntry> premiumListEntries) {
    final Optional<PremiumList> oldPremiumList = PremiumList.get(premiumList.getName());

    // Create the new revision (with its bloom filter) and parent the entries on it.
    final PremiumListRevision newRevision = PremiumListRevision.create(premiumList,
            premiumListEntries.keySet());
    final Key<PremiumListRevision> newRevisionKey = Key.create(newRevision);
    ImmutableSet<PremiumListEntry> parentedEntries = parentPremiumListEntriesOnRevision(
            premiumListEntries.values(), newRevisionKey);

    // Save the new child entities in a series of transactions.
    for (final List<PremiumListEntry> batch : partition(parentedEntries, TRANSACTION_BATCH_SIZE)) {
        ofy().transactNew(new VoidWork() {
            @Override
            public void vrun() {
                ofy().save().entities(batch);
            }
        });
    }

    // Save the new PremiumList and revision itself.
    PremiumList updated = ofy().transactNew(new Work<PremiumList>() {
        @Override
        public PremiumList run() {
            DateTime now = ofy().getTransactionTime();
            // Assert that the premium list hasn't been changed since we started this process.
            PremiumList existing = ofy().load().type(PremiumList.class).parent(getCrossTldKey())
                    .id(premiumList.getName()).now();
            checkState(Objects.equals(existing, oldPremiumList.orNull()),
                    "PremiumList was concurrently edited");
            PremiumList newList = premiumList.asBuilder().setLastUpdateTime(now)
                    .setCreationTime(oldPremiumList.isPresent() ? oldPremiumList.get().creationTime : now)
                    .setRevision(newRevisionKey).build();
            ofy().save().entities(newList, newRevision);
            return newList;
        }
    });
    // Update the cache.
    cachePremiumLists.put(premiumList.getName(), updated);
    // Delete the entities under the old PremiumList.
    if (oldPremiumList.isPresent()) {
        deleteRevisionAndEntriesOfPremiumList(oldPremiumList.get());
    }
    return updated;
}

From source file:com.google.shipshape.analyzers.CheckstyleUtils.java

/**
 * Run Checkstyle against a set of Java files using a specified Checkstyle configuration file.
 *
 * @param context the Shipshape context.
 * @param category the category to report the problems as coming from.
 * @param javaFiles the files to analyze; the map keys are the absolute paths to the file while
 * the values the relative paths to the file from context.file_path. The correct map can be
 * created using {@link CheckstyleUtils#getJavaFiles(ShipshapeContext)}.
 * @param checkstyleConfig the Checkstyle configuration to use.
 * @return the list of problems found by Checkstyle.
 * @throws AnalyzerException//from  w  ww.j  ava2 s  .com
 */
static ImmutableList<Note> runCheckstyle(ShipshapeContext context, String category,
        ImmutableMap<String, String> javaFiles, String checkstyleConfig) throws AnalyzerException {
    ImmutableList<String> commandLine = new ImmutableList.Builder<String>()
            .add(String.format("%s/bin/java", System.getProperties().getProperty("java.home")))
            .add("-jar", checkstyleJar).add("-c", checkstyleConfig).add("-f", "xml").addAll(javaFiles.keySet())
            .build();
    ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
    processBuilder.redirectInput(new File("/dev/null"));
    processBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE);
    processBuilder.redirectError(ProcessBuilder.Redirect.PIPE);
    Process process;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        throw new AnalyzerException(category, context, String.format("error starting command %s", commandLine),
                e);
    }
    byte[] stdout;
    byte[] stderr;
    try {
        // We need to read in the entire stream as pipes can get filled and block the process.
        Future<byte[]> stdoutFuture = threadpool.submit(new ReadAll(process.getInputStream()));
        Future<byte[]> stderrFuture = threadpool.submit(new ReadAll(process.getErrorStream()));
        process.waitFor();
        stdout = stdoutFuture.get();
        stderr = stderrFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new AnalyzerException(category, context,
                String.format("error waiting for command %s", commandLine), e);
    }
    // TODO(rsk): double check what a non-0 exit code means.
    if (process.exitValue() != 0 || stderr.length > 0) {
        throw new AnalyzerException(category, context,
                String.format("command %s failed with %d with stdout \"%s\" and stderr \"%s\"", commandLine,
                        process.exitValue(), decodeWithReplacement(stdout, StandardCharsets.UTF_8),
                        decodeWithReplacement(stderr, StandardCharsets.UTF_8)));
    }

    return parseCheckstyleXml(context, category, javaFiles, stdout);
}

From source file:org.apache.rya.indexing.pcj.fluo.client.PcjAdminClient.java

private static String makeUsage(final ImmutableMap<String, PcjAdminClientCommand> commands) {
    final StringBuilder usage = new StringBuilder();
    usage.append("Usage: ").append(PcjAdminClient.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 .c o 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();
}