Example usage for com.google.common.collect ImmutableSortedMap copyOf

List of usage examples for com.google.common.collect ImmutableSortedMap copyOf

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSortedMap copyOf.

Prototype

public static <K, V> ImmutableSortedMap<K, V> copyOf(
            Iterable<? extends Entry<? extends K, ? extends V>> entries) 

Source Link

Usage

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraExpiringKeyValueService.java

@Override
public void multiPut(Map<String, ? extends Map<Cell, byte[]>> valuesByTable, final long timestamp,
        final long time, final TimeUnit unit) throws KeyAlreadyExistsException {
    List<Callable<Void>> callables = Lists.newArrayList();
    for (Entry<String, ? extends Map<Cell, byte[]>> e : valuesByTable.entrySet()) {
        final String table = e.getKey();
        // We sort here because some key value stores are more efficient if you store adjacent keys together.
        NavigableMap<Cell, byte[]> sortedMap = ImmutableSortedMap.copyOf(e.getValue());

        Iterable<List<Entry<Cell, byte[]>>> partitions = partitionByCountAndBytes(sortedMap.entrySet(),
                getMultiPutBatchCount(), getMultiPutBatchSizeBytes(), table,
                new Function<Entry<Cell, byte[]>, Long>() {

                    @Override//from  w  w  w  .  ja  v  a  2 s .  co  m
                    public Long apply(Entry<Cell, byte[]> entry) {
                        long totalSize = 0;
                        totalSize += entry.getValue().length;
                        totalSize += Cells.getApproxSizeOfCell(entry.getKey());
                        return totalSize;
                    }
                });

        for (final List<Entry<Cell, byte[]>> p : partitions) {
            callables.add(new Callable<Void>() {
                @Override
                public Void call() {
                    Thread.currentThread()
                            .setName("Atlas expiry multiPut of " + p.size() + " cells into " + table);
                    put(table, Maps2.fromEntries(p), timestamp, time, unit);
                    return null;
                }
            });
        }
    }

    List<Future<Void>> futures;
    try {
        futures = executor.invokeAll(callables);
    } catch (InterruptedException e) {
        throw Throwables.throwUncheckedException(e);
    }
    for (Future<Void> future : futures) {
        try {
            future.get();
        } catch (InterruptedException e) {
            throw Throwables.throwUncheckedException(e);
        } catch (ExecutionException e) {
            throw Throwables.rewrapAndThrowUncheckedException(e.getCause());
        }
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLExpiringKeyValueService.java

@Override
public void multiPut(Map<String, ? extends Map<Cell, byte[]>> valuesByTable, final long timestamp,
        final long time, final TimeUnit unit) throws KeyAlreadyExistsException {
    Map<ResultSetFuture, String> resultSetFutures = Maps.newHashMap();
    for (Entry<String, ? extends Map<Cell, byte[]>> e : valuesByTable.entrySet()) {
        final String table = e.getKey();
        // We sort here because some key value stores are more efficient if you store adjacent keys together.
        NavigableMap<Cell, byte[]> sortedMap = ImmutableSortedMap.copyOf(e.getValue());

        Iterable<List<Entry<Cell, byte[]>>> partitions = partitionByCountAndBytes(sortedMap.entrySet(),
                getMultiPutBatchCount(), getMultiPutBatchSizeBytes(), table,
                CQLKeyValueServices.MULTIPUT_ENTRY_SIZING_FUNCTION);

        for (final List<Entry<Cell, byte[]>> p : partitions) {
            List<Entry<Cell, Value>> partition = Lists.transform(p,
                    new Function<Entry<Cell, byte[]>, Entry<Cell, Value>>() {
                        @Override
                        public Entry<Cell, Value> apply(Entry<Cell, byte[]> input) {
                            return Maps.immutableEntry(input.getKey(),
                                    Value.create(input.getValue(), timestamp));
                        }/*from   w w  w. ja  v  a2s.c om*/
                    });
            resultSetFutures.put(getPutPartitionResultSetFuture(table, partition, TransactionType.NONE,
                    CassandraKeyValueServices.convertTtl(time, unit)), table);
        }
    }

    for (Entry<ResultSetFuture, String> result : resultSetFutures.entrySet()) {
        ResultSet resultSet;
        try {
            resultSet = result.getKey().getUninterruptibly();
            resultSet.all();
        } catch (Throwable t) {
            throw Throwables.throwUncheckedException(t);
        }
        CQLKeyValueServices.logTracedQuery(
                getPutQuery(result.getValue(), CassandraKeyValueServices.convertTtl(time, unit)), resultSet,
                session, cqlStatementCache.NORMAL_QUERY);
    }
}

From source file:org.geogit.api.RevTreeImpl.java

public static RevTreeImpl createNodeTree(final ObjectId id, final long size, final int childTreeCount,
        final Map<Integer, Bucket> bucketTrees) {

    Preconditions.checkNotNull(id);/*from w  w w  .  j  ava 2  s  .  co m*/
    Preconditions.checkNotNull(bucketTrees);
    Preconditions.checkArgument(bucketTrees.size() <= RevTree.MAX_BUCKETS);

    ImmutableSortedMap<Integer, Bucket> innerTrees = ImmutableSortedMap.copyOf(bucketTrees);

    return new NodeTree(id, size, childTreeCount, innerTrees);
}

From source file:ec.tss.tsproviders.DataSource.java

@Nonnull
public static DataSource deepCopyOf(@Nonnull String providerName, @Nonnull String version,
        @Nonnull Map<String, String> params) {
    Objects.requireNonNull(providerName, "providerName");
    Objects.requireNonNull(version, "version");
    return new DataSource(providerName, version, ImmutableSortedMap.copyOf(params));
}

From source file:com.google.caliper.runner.CaliperMain.java

public static void exitlessMain(String[] args, PrintWriter stdout, PrintWriter stderr)
        throws InvalidCommandException, InvalidBenchmarkException, InvalidConfigurationException {
    @Nullable/*from w  w  w.j av a 2  s .c  o m*/
    String legacyCaliperEnv = System.getenv(LEGACY_ENV);
    if (!Strings.isNullOrEmpty(legacyCaliperEnv)) {
        System.err.println("Legacy Caliper is no more. " + LEGACY_ENV + " has no effect.");
    }
    try {
        // TODO(gak): see if there's a better way to deal with options. probably a module
        Injector optionsInjector = Guice.createInjector(new OptionsModule(args));
        CaliperOptions options = optionsInjector.getInstance(CaliperOptions.class);
        Module runnerModule = new ExperimentingRunnerModule();
        Class<?> benchmarkClass = benchmarkClassForName(options.benchmarkClassName());
        Injector injector = optionsInjector.createChildInjector(new BenchmarkClassModule(benchmarkClass),
                new OutputModule(stdout, stderr), new BridgeModule(), new GsonModule(), new ConfigModule(),
                new ServiceModule(), runnerModule);
        if (options.printConfiguration()) {
            stdout.println("Configuration:");
            ImmutableSortedMap<String, String> sortedProperties = ImmutableSortedMap
                    .copyOf(injector.getInstance(CaliperConfig.class).properties());
            for (Entry<String, String> entry : sortedProperties.entrySet()) {
                stdout.printf("  %s = %s%n", entry.getKey(), entry.getValue());
            }
        }
        // check that the parameters are valid
        injector.getInstance(BenchmarkClass.class).validateParameters(options.userParameters());
        ServiceManager serviceManager = injector.getInstance(ServiceManager.class);
        serviceManager.startAsync().awaitHealthy();
        try {
            CaliperRun run = injector.getInstance(CaliperRun.class); // throws wrapped ICE, IBE
            run.run(); // throws IBE
        } finally {
            try {
                // We have some shutdown logic to ensure that files are cleaned up so give it a chance to
                // run
                serviceManager.stopAsync().awaitStopped(10, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                // Thats fine
            }
        }
    } catch (CreationException e) {
        propogateIfCaliperException(e.getCause());
        throw e;
    } catch (ProvisionException e) {
        propogateIfCaliperException(e.getCause());
        for (Message message : e.getErrorMessages()) {
            propogateIfCaliperException(message.getCause());
        }
        throw e;
    }

    // courtesy flush
    stderr.flush();
    stdout.flush();
}

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

@Override
public ImmutableList<? extends Step> getBuildSteps(BuildContext buildContext,
        BuildableContext buildableContext) {
    return ImmutableList.of(new AbstractExecutionStep("listing_exo_contents") {
        @Override/* w  w w.  ja va 2s . com*/
        public StepExecutionResult execute(ExecutionContext context) throws IOException, InterruptedException {
            trigger.verify(context);
            ConcurrentHashMap<String, SortedSet<String>> contents = new ConcurrentHashMap<>();
            context.getAndroidDevicesHelper().get().adbCallOrThrow("listing_exo_contents_for_device",
                    (device) -> {
                        device.mkDirP(ExopackageInstaller.EXOPACKAGE_INSTALL_ROOT.toString());
                        contents.put(device.getSerialNumber(),
                                device.listDirRecursive(ExopackageInstaller.EXOPACKAGE_INSTALL_ROOT).stream()
                                        .map(Path::toString)
                                        .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())));
                        return true;
                    }, true);
            getProjectFilesystem().mkdirs(outputPath.getParent());
            getProjectFilesystem().writeContentsToPath(
                    serializeDirectoryContents(ImmutableSortedMap.copyOf(contents)), outputPath);
            buildableContext.recordArtifact(outputPath);
            return StepExecutionResults.SUCCESS;
        }
    });
}

From source file:ec.tss.tsproviders.DataSet.java

@Nonnull
public static DataSet deepCopyOf(@Nonnull DataSource dataSource, @Nonnull Kind kind,
        @Nonnull Map<String, String> params) {
    Objects.requireNonNull(dataSource, "dataSource");
    Objects.requireNonNull(kind, "kind");
    return new DataSet(dataSource, kind, ImmutableSortedMap.copyOf(params));
}

From source file:com.github.gv2011.util.icol.guava.ISortedMapWrapper.java

@Override
public ISortedMap<K, V> headMap(final K toKey) {
    return new ISortedMapWrapper<>(ImmutableSortedMap.copyOf(delegate.headMap(toKey)));
}

From source file:com.github.gv2011.util.icol.guava.ISortedMapWrapper.java

@Override
public ISortedMap<K, V> tailMap(final K fromKey) {
    return new ISortedMapWrapper<>(ImmutableSortedMap.copyOf(delegate.tailMap(fromKey)));
}

From source file:com.facebook.buck.core.rules.impl.SymlinkTree.java

/**
 * Creates an instance of {@link SymlinkTree}
 *
 * @param category A name used in the symlink steps
 * @param target The target for this rule
 * @param filesystem The filesystem that the tree lives on
 * @param root The directory to create symlinks in
 * @param links A map of path within the link tree to the target of the symlikm
 * @param directoriesToMerge A map of relative paths within the link tree into which files from
 *     the value will be recursively linked. e.g. if a file at /tmp/foo/bar should be linked as
 *     /tmp/symlink-root/subdir/bar, the map should contain {Paths.get("subdir"),
 *     SourcePath(Paths.get("tmp", "foo")) }
 * @param ruleFinder Used to iterate over {@code directoriesToMerge} in order get the build time
 *//*  ww  w. j av a 2s .c om*/
public SymlinkTree(String category, BuildTarget target, ProjectFilesystem filesystem, Path root,
        ImmutableMap<Path, SourcePath> links, ImmutableMultimap<Path, SourcePath> directoriesToMerge,
        SourcePathRuleFinder ruleFinder) {
    super(target, filesystem);
    this.category = category;
    this.directoriesToMerge = directoriesToMerge;

    this.buildDeps = directoriesToMerge.values().stream().map(ruleFinder::getRule).filter(Optional::isPresent)
            .map(Optional::get).collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));

    Preconditions.checkState(!root.isAbsolute(), "Expected symlink tree root to be relative: %s", root);

    this.root = root;
    this.links = ImmutableSortedMap.copyOf(links);

    this.type = category + "_symlink_tree";
}