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

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

Introduction

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

Prototype

public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() 

Source Link

Usage

From source file:org.apache.calcite.rel.core.Match.java

/** Creates an immutable copy of a map of sorted sets. */
private static <K extends Comparable<K>, V> ImmutableSortedMap<K, SortedSet<V>> copy(Map<K, SortedSet<V>> map) {
    final ImmutableSortedMap.Builder<K, SortedSet<V>> b = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<K, SortedSet<V>> e : map.entrySet()) {
        b.put(e.getKey(), ImmutableSortedSet.copyOf(e.getValue()));
    }//from w w  w. j  a  va  2 s . co m
    return b.build();
}

From source file:org.apache.calcite.util.EquivalenceSet.java

/** Returns a map of the canonical element in each equivalence class to the
 * set of elements in that class. The keys are sorted in natural order, as
 * are the elements within each key. */
public SortedMap<E, SortedSet<E>> map() {
    final TreeMultimap<E, E> multimap = TreeMultimap.create();
    for (Map.Entry<E, E> entry : parents.entrySet()) {
        multimap.put(entry.getValue(), entry.getKey());
    }//from  www .  ja  va  2s.  c  o  m
    // Create an immutable copy. Keys and values remain in sorted order.
    final ImmutableSortedMap.Builder<E, SortedSet<E>> builder = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<E, Collection<E>> entry : multimap.asMap().entrySet()) {
        builder.put(entry.getKey(), ImmutableSortedSet.copyOf(entry.getValue()));
    }
    return builder.build();
}

From source file:com.google.devtools.build.lib.skyframe.serialization.ImmutableMapCodec.java

@Override
public ImmutableMap<?, V> deserialize(DeserializationContext context, CodedInputStream codedIn)
        throws SerializationException, IOException {
    int length = codedIn.readInt32();
    if (length < 0) {
        throw new SerializationException("Expected non-negative length: " + length);
    }//from w  w  w.j a  v  a2 s  . c o  m
    if (codedIn.readBool()) {
        return buildMap(ImmutableSortedMap.naturalOrder(), length, context, codedIn);
    } else {
        return buildMap(ImmutableMap.builderWithExpectedSize(length), length, context, codedIn);
    }
}

From source file:org.gradle.api.internal.changedetection.state.CacheBackedTaskHistoryRepository.java

public History getHistory(final TaskInternal task) {
    final TaskExecutionList previousExecutions = loadPreviousExecutions(task);
    final LazyTaskExecution currentExecution = new LazyTaskExecution();
    currentExecution.snapshotRepository = snapshotRepository;
    currentExecution.setOutputPropertyNamesForCacheKey(getOutputPropertyNamesForCacheKey(task));
    currentExecution.setDeclaredOutputFilePaths(getDeclaredOutputFilePaths(task));
    final LazyTaskExecution previousExecution = findBestMatchingPreviousExecution(currentExecution,
            previousExecutions.executions);
    if (previousExecution != null) {
        previousExecution.snapshotRepository = snapshotRepository;
    }/*  w  w  w  . j a  va  2s  . c  om*/

    return new History() {
        public TaskExecution getPreviousExecution() {
            return previousExecution;
        }

        public TaskExecution getCurrentExecution() {
            return currentExecution;
        }

        public void update() {
            previousExecutions.executions.addFirst(currentExecution);
            if (currentExecution.inputFilesSnapshotIds == null && currentExecution.inputFilesSnapshot != null) {
                ImmutableSortedMap.Builder<String, Long> builder = ImmutableSortedMap.naturalOrder();
                for (Map.Entry<String, FileCollectionSnapshot> entry : currentExecution.inputFilesSnapshot
                        .entrySet()) {
                    builder.put(entry.getKey(), snapshotRepository.add(entry.getValue()));
                }
                currentExecution.inputFilesSnapshotIds = builder.build();
            }
            if (currentExecution.outputFilesSnapshotIds == null
                    && currentExecution.outputFilesSnapshot != null) {
                ImmutableSortedMap.Builder<String, Long> builder = ImmutableSortedMap.naturalOrder();
                for (Map.Entry<String, FileCollectionSnapshot> entry : currentExecution.outputFilesSnapshot
                        .entrySet()) {
                    builder.put(entry.getKey(), snapshotRepository.add(entry.getValue()));
                }
                currentExecution.outputFilesSnapshotIds = builder.build();
            }
            if (currentExecution.discoveredFilesSnapshotId == null
                    && currentExecution.discoveredFilesSnapshot != null) {
                currentExecution.discoveredFilesSnapshotId = snapshotRepository
                        .add(currentExecution.discoveredFilesSnapshot);
            }
            while (previousExecutions.executions.size() > MAX_HISTORY_ENTRIES) {
                LazyTaskExecution execution = previousExecutions.executions.removeLast();
                if (execution.inputFilesSnapshotIds != null) {
                    for (Long id : execution.inputFilesSnapshotIds.values()) {
                        snapshotRepository.remove(id);
                    }
                }
                if (execution.outputFilesSnapshotIds != null) {
                    for (Long id : execution.outputFilesSnapshotIds.values()) {
                        snapshotRepository.remove(id);
                    }
                }
                if (execution.discoveredFilesSnapshotId != null) {
                    snapshotRepository.remove(execution.discoveredFilesSnapshotId);
                }
            }
            taskHistoryCache.put(task.getPath(), previousExecutions.snapshot());
        }
    };
}

From source file:com.facebook.buck.versions.TargetNodeTranslator.java

public <A extends Comparable<?>, B> Optional<ImmutableSortedMap<A, B>> translateSortedMap(
        ImmutableSortedMap<A, B> val) {
    boolean modified = false;
    ImmutableSortedMap.Builder<A, B> builder = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<A, B> ent : val.entrySet()) {
        Optional<A> key = translate(ent.getKey());
        Optional<B> value = translate(ent.getValue());
        modified = modified || key.isPresent() || value.isPresent();
        builder.put(key.orElse(ent.getKey()), value.orElse(ent.getValue()));
    }/*  w  w w. j  a  v a  2  s  .  com*/
    return modified ? Optional.of(builder.build()) : Optional.empty();
}

From source file:com.google.enterprise.connector.persist.MockPersistentStore.java

@Override
public ImmutableMap<StoreContext, ConnectorStamps> getInventory() {
    ImmutableMap.Builder<StoreContext, ConnectorStamps> builder;
    if (sortInventory) {
        builder = ImmutableSortedMap.naturalOrder();
    } else {/*from   w w w. j a  v a  2 s. c o m*/
        builder = ImmutableMap.builder();
    }
    Set<StoreContext> instances = new HashSet<StoreContext>();
    synchronized (this) {
        for (StoreKey key : storeMap.keySet()) {
            instances.add(key.context);
        }
        for (StoreContext context : instances) {
            builder.put(context, new ConnectorStamps(getStamp(context, CHECKPOINT),
                    getStamp(context, CONFIGURATION), getStamp(context, SCHEDULE)));
        }
    }
    return builder.build();
}

From source file:org.kiji.schema.impl.hbase.HBasePagedKijiResult.java

/**
 * Create a new {@link HBasePagedKijiResult}.
 *
 * @param entityId EntityId of the row from which to read cells.
 * @param dataRequest KijiDataRequest defining the values to retrieve.
 * @param table The table being viewed.//from   w  w w  .j a  v a2  s .  c o m
 * @param layout The layout of the table.
 * @param columnTranslator A column name translator for the table.
 * @param decoderProvider A cell decoder provider for the table.
 */
public HBasePagedKijiResult(final EntityId entityId, final KijiDataRequest dataRequest,
        final HBaseKijiTable table, final KijiTableLayout layout,
        final HBaseColumnNameTranslator columnTranslator, final CellDecoderProvider decoderProvider) {
    mEntityId = entityId;
    mDataRequest = dataRequest;
    mLayout = layout;
    mColumnTranslator = columnTranslator;
    mDecoderProvider = decoderProvider;
    mTable = table;
    mCloser = Closer.create();

    final ImmutableSortedMap.Builder<KijiColumnName, Iterable<KijiCell<T>>> columnResults = ImmutableSortedMap
            .naturalOrder();

    for (Column columnRequest : mDataRequest.getColumns()) {
        final PagedColumnIterable columnIterable = new PagedColumnIterable(columnRequest);
        mCloser.register(columnIterable);
        columnResults.put(columnRequest.getColumnName(), columnIterable);
    }

    mColumnResults = columnResults.build();
}

From source file:com.moz.fiji.schema.impl.hbase.HBasePagedFijiResult.java

/**
 * Create a new {@link HBasePagedFijiResult}.
 *
 * @param entityId EntityId of the row from which to read cells.
 * @param dataRequest FijiDataRequest defining the values to retrieve.
 * @param table The table being viewed./*from w  w  w .j a v a  2 s  .com*/
 * @param layout The layout of the table.
 * @param columnTranslator A column name translator for the table.
 * @param decoderProvider A cell decoder provider for the table.
 */
public HBasePagedFijiResult(final EntityId entityId, final FijiDataRequest dataRequest,
        final HBaseFijiTable table, final FijiTableLayout layout,
        final HBaseColumnNameTranslator columnTranslator, final CellDecoderProvider decoderProvider) {
    mEntityId = entityId;
    mDataRequest = dataRequest;
    mLayout = layout;
    mColumnTranslator = columnTranslator;
    mDecoderProvider = decoderProvider;
    mTable = table;
    mCloser = Closer.create();

    final ImmutableSortedMap.Builder<FijiColumnName, Iterable<FijiCell<T>>> columnResults = ImmutableSortedMap
            .naturalOrder();

    for (Column columnRequest : mDataRequest.getColumns()) {
        final PagedColumnIterable columnIterable = new PagedColumnIterable(columnRequest);
        mCloser.register(columnIterable);
        columnResults.put(columnRequest.getColumnName(), columnIterable);
    }

    mColumnResults = columnResults.build();
}

From source file:com.facebook.buck.features.haskell.HaskellDescriptionUtils.java

/**
 * Create a Haskell compile rule that compiles all the given haskell sources in one step and pulls
 * interface files from all transitive haskell dependencies.
 *///from   w w  w  . j av a 2s .c  om
private static HaskellCompileRule createCompileRule(BuildTarget target, ProjectFilesystem projectFilesystem,
        BuildRuleParams baseParams, ActionGraphBuilder graphBuilder, SourcePathRuleFinder ruleFinder,
        ImmutableSet<BuildRule> deps, HaskellPlatform platform, Linker.LinkableDepType depType,
        boolean hsProfile, Optional<String> main, Optional<HaskellPackageInfo> packageInfo,
        ImmutableList<String> flags, HaskellSources sources) {

    CxxPlatform cxxPlatform = platform.getCxxPlatform();

    Map<BuildTarget, ImmutableList<String>> depFlags = new TreeMap<>();
    Map<BuildTarget, ImmutableList<SourcePath>> depIncludes = new TreeMap<>();
    ImmutableSortedMap.Builder<String, HaskellPackage> exposedPackagesBuilder = ImmutableSortedMap
            .naturalOrder();
    ImmutableSortedMap.Builder<String, HaskellPackage> packagesBuilder = ImmutableSortedMap.naturalOrder();
    new AbstractBreadthFirstTraversal<BuildRule>(deps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override
        public Iterable<BuildRule> visit(BuildRule rule) {
            Iterable<BuildRule> ruleDeps = empty;
            if (rule instanceof HaskellCompileDep) {
                HaskellCompileDep haskellCompileDep = (HaskellCompileDep) rule;
                ruleDeps = haskellCompileDep.getCompileDeps(platform);
                HaskellCompileInput compileInput = haskellCompileDep.getCompileInput(platform, depType,
                        hsProfile);
                depFlags.put(rule.getBuildTarget(), compileInput.getFlags());
                depIncludes.put(rule.getBuildTarget(), compileInput.getIncludes());

                // We add packages from first-order deps as expose modules, and transitively included
                // packages as hidden ones.
                boolean firstOrderDep = deps.contains(rule);
                for (HaskellPackage pkg : compileInput.getPackages()) {
                    if (firstOrderDep) {
                        exposedPackagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
                    } else {
                        packagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
                    }
                }
            }
            return ruleDeps;
        }
    }.start();

    Collection<CxxPreprocessorInput> cxxPreprocessorInputs = CxxPreprocessables
            .getTransitiveCxxPreprocessorInput(cxxPlatform, graphBuilder, deps);
    ExplicitCxxToolFlags.Builder toolFlagsBuilder = CxxToolFlags.explicitBuilder();
    PreprocessorFlags.Builder ppFlagsBuilder = PreprocessorFlags.builder();
    toolFlagsBuilder.setPlatformFlags(
            StringArg.from(CxxSourceTypes.getPlatformPreprocessFlags(cxxPlatform, CxxSource.Type.C)));
    for (CxxPreprocessorInput input : cxxPreprocessorInputs) {
        ppFlagsBuilder.addAllIncludes(input.getIncludes());
        ppFlagsBuilder.addAllFrameworkPaths(input.getFrameworks());
        toolFlagsBuilder.addAllRuleFlags(input.getPreprocessorFlags().get(CxxSource.Type.C));
    }
    ppFlagsBuilder.setOtherFlags(toolFlagsBuilder.build());
    PreprocessorFlags ppFlags = ppFlagsBuilder.build();

    ImmutableList<String> compileFlags = ImmutableList.<String>builder().addAll(platform.getCompilerFlags())
            .addAll(flags).addAll(Iterables.concat(depFlags.values())).build();

    ImmutableList<SourcePath> includes = ImmutableList.copyOf(Iterables.concat(depIncludes.values()));

    ImmutableSortedMap<String, HaskellPackage> exposedPackages = exposedPackagesBuilder.build();
    ImmutableSortedMap<String, HaskellPackage> packages = packagesBuilder.build();

    return HaskellCompileRule.from(target, projectFilesystem, baseParams, ruleFinder,
            platform.getCompiler().resolve(graphBuilder), platform.getHaskellVersion(), compileFlags, ppFlags,
            cxxPlatform, depType == Linker.LinkableDepType.STATIC ? PicType.PDC : PicType.PIC, hsProfile, main,
            packageInfo, includes, exposedPackages, packages, sources,
            CxxSourceTypes.getPreprocessor(cxxPlatform, CxxSource.Type.C).resolve(graphBuilder));
}

From source file:org.voltdb.sysprocs.saverestore.StreamSnapshotRequestConfig.java

private SortedMap<Long, Long> parsePostSnapshotTasks(JSONObject jsData) {
    if (jsData != null) {
        try {//from   w ww.  ja  va 2 s.  co m
            JSONObject cts = jsData.optJSONObject("postSnapshotTasks");
            if (cts != null) {
                // Get the set of new partitions to add
                JSONObject rangeObj = cts.getJSONObject("ranges");
                Iterator rangeKey = rangeObj.keys();

                ImmutableSortedMap.Builder<Long, Long> rangeBuilder = ImmutableSortedMap.naturalOrder();
                while (rangeKey.hasNext()) {
                    String rangeStartStr = (String) rangeKey.next();
                    long rangeStart = Long.parseLong(rangeStartStr);
                    long rangeEnd = rangeObj.getLong(rangeStartStr);
                    rangeBuilder.put(rangeStart, rangeEnd);
                }

                return rangeBuilder.build();
            }
        } catch (JSONException e) {
            SNAP_LOG.warn("Failed to parse completion task information", e);
        }
    }

    return null;
}