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

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

Introduction

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

Prototype

public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) 

Source Link

Usage

From source file:org.thelq.stackexchange.dbimport.Controller.java

public void initMetadataMap(SessionFactory sessionFactory) {
    ImmutableSortedMap.Builder<String, ImmutableMap<String, Type>> metadataMapBuilder = ImmutableSortedMap
            .orderedBy(String.CASE_INSENSITIVE_ORDER);
    for (Map.Entry<String, ClassMetadata> curEntry : sessionFactory.getAllClassMetadata().entrySet()) {
        ClassMetadata tableDataRaw = curEntry.getValue();
        ImmutableMap.Builder<String, Type> propertiesBuilder = ImmutableMap.builder();
        propertiesBuilder.put(tableDataRaw.getIdentifierPropertyName(), tableDataRaw.getIdentifierType());
        for (String curPropertyName : tableDataRaw.getPropertyNames())
            propertiesBuilder.put(curPropertyName, tableDataRaw.getPropertyType(curPropertyName));
        metadataMapBuilder.put(curEntry.getKey(), propertiesBuilder.build());
    }/*from  w  ww.  j a va2s . c om*/
    metadataMap = metadataMapBuilder.build();
}

From source file:de.cosmocode.palava.ipc.xml.rpc.adapters.ObjectAdapter.java

@Inject
public ObjectAdapter(@XmlRpc ObjectFactory factory, Adapter<Value, Boolean> booleanAdapter,
        Adapter<Value, Date> dateAdapter, Adapter<Value, Double> doubleAdapter,
        Adapter<Value, InputStream> streamAdapter, Adapter<Value, Integer> integerAdapter,
        Adapter<Value, List<Object>> listAdapter, Adapter<Value, Map<String, Object>> mapAdapter,
        Adapter<Value, Number> numberAdapter, Adapter<Value, String> stringAdapter) {

    Preconditions.checkNotNull(factory, "Factory");
    this.nullValue = factory.createValue();
    this.nullValue.getContent().add(factory.createValueString("null"));

    final Builder<Class<?>, Adapter<Value, ?>> builder = ImmutableSortedMap.orderedBy(HIERARCHY);

    builder.put(Number.class, numberAdapter);
    builder.put(Boolean.class, booleanAdapter);
    builder.put(Calendar.class, Adapters.composeEncoder(dateAdapter, Calendars.getTime()));
    builder.put(Date.class, dateAdapter);
    builder.put(Double.class, doubleAdapter);
    builder.put(InputStream.class, streamAdapter);
    builder.put(Integer.class, integerAdapter);
    builder.put(List.class, listAdapter);
    builder.put(Map.class, mapAdapter);
    builder.put(String.class, stringAdapter);

    this.adapters = builder.build();
}

From source file:com.palantir.atlasdb.transaction.impl.CachingTransaction.java

@Override
public SortedMap<byte[], RowResult<byte[]>> getRows(String tableName, Iterable<byte[]> rows,
        ColumnSelection columnSelection) {
    if (Iterables.isEmpty(rows)) {
        log.info("Attempted getRows on '{}' table and {} with empty rows argument", tableName, columnSelection);
        return AbstractTransaction.EMPTY_SORTED_ROWS;
    }//from  w  w  w. ja v  a  2 s .  c  om

    ConcurrentMap<Cell, byte[]> colCache = getColCacheForTable(tableName);
    if (columnSelection.allColumnsSelected()) {
        SortedMap<byte[], RowResult<byte[]>> loaded = super.getRows(tableName, rows, columnSelection);
        cacheLoadedRows(colCache, loaded.values());
        return loaded;
    } else {
        Set<byte[]> toLoad = Sets.newHashSet();
        ImmutableSortedMap.Builder<byte[], RowResult<byte[]>> inCache = ImmutableSortedMap
                .orderedBy(UnsignedBytes.lexicographicalComparator());
        for (byte[] row : rows) {
            ImmutableSortedMap.Builder<byte[], byte[]> matches = ImmutableSortedMap
                    .orderedBy(UnsignedBytes.lexicographicalComparator());
            boolean nonEmpty = false;
            boolean shouldLoad = false;
            for (byte[] col : columnSelection.getSelectedColumns()) {
                byte[] val = colCache.get(Cell.create(row, col));
                if (val == null) {
                    shouldLoad = true;
                    break;
                } else if (val.length != 0) {
                    matches.put(col, val);
                    nonEmpty = true;
                }
            }
            if (shouldLoad) {
                toLoad.add(row);
            } else if (nonEmpty) {
                inCache.put(row, RowResult.create(row, matches.build()));
            }
        }
        SortedMap<byte[], RowResult<byte[]>> results = super.getRows(tableName, toLoad, columnSelection);
        cacheLoadedRows(colCache, results.values());
        inCache.putAll(results);
        return inCache.build();
    }
}

From source file:co.cask.cdap.data2.transaction.stream.StreamConsumerStateStore.java

@Override
public final void save(Iterable<? extends StreamConsumerState> states) throws IOException {
    ImmutableSortedMap.Builder<byte[], byte[]> values = ImmutableSortedMap.orderedBy(Bytes.BYTES_COMPARATOR);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutput output = new DataOutputStream(os);
    for (StreamConsumerState state : states) {
        os.reset();//from  ww w  .  ja v  a 2s .c  o m
        encodeOffsets(state.getState(), output);
        values.put(getColumn(state.getGroupId(), state.getInstanceId()), os.toByteArray());
    }

    store(streamId.toBytes(), values.build());
}

From source file:com.palantir.atlasdb.keyvalue.impl.RowResults.java

public static <T> RowResult<T> merge(RowResult<T> base, RowResult<T> overwrite) {
    Validate.isTrue(Arrays.equals(base.getRowName(), overwrite.getRowName()));
    Builder<byte[], T> colBuilder = ImmutableSortedMap.orderedBy(UnsignedBytes.lexicographicalComparator());
    colBuilder.putAll(overwrite.getColumns());
    colBuilder.putAll(Maps.difference(base.getColumns(), overwrite.getColumns()).entriesOnlyOnLeft());
    return RowResult.create(base.getRowName(), colBuilder.build());
}

From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java

/**
 * The Collection provided to this function has to be sorted and strictly increasing.
 *///  w w  w  .j ava2  s .c  om
public static <T> Iterator<RowResult<T>> createRowView(final Collection<Map.Entry<Cell, T>> sortedIterator) {
    final PeekingIterator<Entry<Cell, T>> it = Iterators.peekingIterator(sortedIterator.iterator());
    Iterator<Map.Entry<byte[], SortedMap<byte[], T>>> resultIt = new AbstractIterator<Map.Entry<byte[], SortedMap<byte[], T>>>() {
        byte[] row = null;
        SortedMap<byte[], T> map = null;

        @Override
        protected Entry<byte[], SortedMap<byte[], T>> computeNext() {
            if (!it.hasNext()) {
                return endOfData();
            }
            row = it.peek().getKey().getRowName();
            ImmutableSortedMap.Builder<byte[], T> mapBuilder = ImmutableSortedMap
                    .orderedBy(UnsignedBytes.lexicographicalComparator());
            while (it.hasNext()) {
                Entry<Cell, T> peek = it.peek();
                if (!Arrays.equals(peek.getKey().getRowName(), row)) {
                    break;
                }
                mapBuilder.put(peek.getKey().getColumnName(), peek.getValue());
                it.next();
            }
            map = mapBuilder.build();
            return Maps.immutableEntry(row, map);
        }
    };
    return RowResults.viewOfEntries(resultIt);
}

From source file:com.google.devtools.build.lib.rules.cpp.CcIncLibrary.java

@Override
public ConfiguredTarget create(final RuleContext ruleContext) throws RuleErrorException, InterruptedException {
    FeatureConfiguration featureConfiguration = CcCommon.configureFeatures(ruleContext);
    PathFragment packageFragment = ruleContext.getPackageDirectory();

    // The rule needs a unique location for the include directory, which doesn't conflict with any
    // other rule. For that reason, the include directory is at:
    // configuration/package_name/_/target_name
    // And then the symlink is placed at:
    // configuration/package_name/_/target_name/package_name
    // So that these inclusions can be resolved correctly:
    // #include "package_name/a.h"
    ////from  ww w  .jav a 2  s  . co m
    // The target of the symlink is:
    // package_name/targetPrefix/
    // All declared header files must be below that directory.
    String expandedIncSymlinkAttr = ruleContext.attributes().get("prefix", Type.STRING);

    // We use an additional "_" directory here to avoid conflicts between this and previous Blaze
    // versions. Previous Blaze versions created a directory symlink; the new version does not
    // detect that the output directory isn't a directory, and tries to put the symlinks into what
    // is actually a symlink into the source tree.
    PathFragment includeDirectory = new PathFragment("_").getRelative(ruleContext.getTarget().getName());
    Root configIncludeDirectory = ruleContext.getConfiguration()
            .getIncludeDirectory(ruleContext.getRule().getRepository());
    PathFragment includePath = configIncludeDirectory.getExecPath().getRelative(packageFragment)
            .getRelative(includeDirectory);
    Path includeRoot = configIncludeDirectory.getPath().getRelative(packageFragment)
            .getRelative(includeDirectory);

    // For every source artifact, we compute a virtual artifact that is below the include directory.
    // These are used for include checking.
    PathFragment prefixFragment = packageFragment.getRelative(expandedIncSymlinkAttr);
    if (!prefixFragment.isNormalized()) {
        ruleContext.attributeWarning("prefix", "should not contain '.' or '..' elements");
    }
    ImmutableSortedMap.Builder<Artifact, Artifact> virtualArtifactMapBuilder = ImmutableSortedMap
            .orderedBy(Artifact.EXEC_PATH_COMPARATOR);
    prefixFragment = prefixFragment.normalize();
    ImmutableList<Artifact> hdrs = ruleContext.getPrerequisiteArtifacts("hdrs", Mode.TARGET).list();
    for (Artifact src : hdrs) {
        // All declared header files must start with package/targetPrefix.
        if (!src.getRootRelativePath().startsWith(prefixFragment)) {
            ruleContext.attributeError("hdrs",
                    src + " does not start with '" + prefixFragment.getPathString() + "'");
            return null;
        }

        // Remove the targetPrefix from within the exec path of the source file, and prepend the
        // unique directory prefix, e.g.:
        // third_party/foo/1.2/bar/a.h -> third_party/foo/name/third_party/foo/bar/a.h
        PathFragment suffix = src.getRootRelativePath().relativeTo(prefixFragment);
        PathFragment virtualPath = includeDirectory.getRelative(packageFragment).getRelative(suffix);

        // These virtual artifacts have the symlink action as generating action.
        Artifact virtualArtifact = ruleContext.getPackageRelativeArtifact(virtualPath, configIncludeDirectory);
        virtualArtifactMapBuilder.put(virtualArtifact, src);
    }
    ImmutableSortedMap<Artifact, Artifact> virtualArtifactMap = virtualArtifactMapBuilder.build();
    ruleContext.registerAction(
            new CreateIncSymlinkAction(ruleContext.getActionOwner(), virtualArtifactMap, includeRoot));

    CcLibraryHelper.Info info = new CcLibraryHelper(ruleContext, semantics, featureConfiguration)
            .addIncludeDirs(Arrays.asList(includePath)).addPublicHeaders(virtualArtifactMap.keySet())
            .addDeps(ruleContext.getPrerequisites("deps", Mode.TARGET)).build();

    // cc_inc_library doesn't compile any file - no compilation outputs available.
    InstrumentedFilesProvider instrumentedFilesProvider = new CcCommon(ruleContext)
            .getInstrumentedFilesProvider(new ArrayList<Artifact>(), /*withBaselineCoverage=*/true);

    return new RuleConfiguredTargetBuilder(ruleContext).addProviders(info.getProviders())
            .addSkylarkTransitiveInfo(CcSkylarkApiProvider.NAME, new CcSkylarkApiProvider())
            .addOutputGroups(info.getOutputGroups())
            .add(InstrumentedFilesProvider.class, instrumentedFilesProvider)
            .add(RunfilesProvider.class, RunfilesProvider.simple(Runfiles.EMPTY)).build();
}

From source file:com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService.java

private <T> ClosableIterator<RowResult<T>> getRangeInternal(String tableName, final RangeRequest range,
        final ResultProducer<T> resultProducer) {
    ConcurrentNavigableMap<Key, byte[]> tableMap = getTableMap(tableName).entries;
    if (range.isReverse()) {
        tableMap = tableMap.descendingMap();
    }/*from ww  w . ja  v a 2s .co  m*/
    if (range.getStartInclusive().length != 0) {
        if (range.isReverse()) {
            Cell startCell = Cells.createLargestCellForRow(range.getStartInclusive());
            tableMap = tableMap.tailMap(new Key(startCell, Long.MIN_VALUE));
        } else {
            Cell startCell = Cells.createSmallestCellForRow(range.getStartInclusive());
            tableMap = tableMap.tailMap(new Key(startCell, Long.MIN_VALUE));
        }
    }
    if (range.getEndExclusive().length != 0) {
        if (range.isReverse()) {
            Cell endCell = Cells.createLargestCellForRow(range.getEndExclusive());
            tableMap = tableMap.headMap(new Key(endCell, Long.MAX_VALUE));
        } else {
            Cell endCell = Cells.createSmallestCellForRow(range.getEndExclusive());
            tableMap = tableMap.headMap(new Key(endCell, Long.MAX_VALUE));
        }
    }
    final PeekingIterator<Entry<Key, byte[]>> it = Iterators.peekingIterator(tableMap.entrySet().iterator());
    return ClosableIterators.wrap(new AbstractIterator<RowResult<T>>() {
        @Override
        protected RowResult<T> computeNext() {
            while (true) {
                if (!it.hasNext()) {
                    return endOfData();
                }
                ImmutableSortedMap.Builder<byte[], T> result = ImmutableSortedMap
                        .orderedBy(UnsignedBytes.lexicographicalComparator());
                Key key = it.peek().getKey();
                byte[] row = key.row;
                Iterator<Entry<Key, byte[]>> cellIter = takeCell(it, key);
                collectValueForTimestamp(key.col, cellIter, result, range, resultProducer);

                while (it.hasNext()) {
                    if (!it.peek().getKey().matchesRow(row)) {
                        break;
                    }
                    key = it.peek().getKey();
                    cellIter = takeCell(it, key);
                    collectValueForTimestamp(key.col, cellIter, result, range, resultProducer);
                }
                SortedMap<byte[], T> columns = result.build();
                if (!columns.isEmpty()) {
                    return RowResult.create(row, columns);
                }
            }
        }

    });
}

From source file:com.google.devtools.build.lib.rules.android.ApplicationManifest.java

private static Map<Artifact, Label> getMergeeManifests(Iterable<ResourceContainer> resourceContainers) {
    ImmutableSortedMap.Builder<Artifact, Label> builder = ImmutableSortedMap
            .orderedBy(Artifact.EXEC_PATH_COMPARATOR);
    for (ResourceContainer r : resourceContainers) {
        if (r.isManifestExported()) {
            builder.put(r.getManifest(), r.getLabel());
        }/*w ww.  java  2s .  c om*/
    }
    return builder.build();
}

From source file:com.google.cloud.dataflow.sdk.runners.worker.IsmReader.java

/**
 * Initializes the footer, Bloom filter and index if they have not yet been initialized.
 * Returns a {@link SeekableByteChannel} at an arbitrary position within the stream.
 * Callers should re-position the channel to their desired location.
 *//*from  w w w  . j  a va 2 s  . co m*/
private SeekableByteChannel initializeForKeyedRead() throws IOException {
    SeekableByteChannel inChannel = openConnection(filename);
    if (index != null) {
        checkState(footer != null, "Footer expected to have been initialized.");
        checkState(bloomFilter != null, "Bloom filter expected to have been initialized.");
        return inChannel;
    }
    checkState(bloomFilter == null, "Bloom filter not expected to have been initialized.");

    initializeFooter(inChannel);

    // Set the position to where the bloom filter is and read it in.
    inChannel.position(footer.getBloomFilterPosition());
    bloomFilter = ScalableBloomFilterCoder.of().decode(Channels.newInputStream(inChannel), Context.NESTED);

    // The index follows the bloom filter directly, so we do not need to do a seek here.
    // This is an optimization.
    @SuppressWarnings("resource")
    LegacyReaderIterator<KV<RandomAccessData, Long>> iterator = new IsmReaderIterator<RandomAccessData, Long>(
            inChannel, new RandomAccessData(), RandomAccessDataCoder.of(), VarLongCoder.of(),
            length - Footer.FIXED_LENGTH);
    ImmutableSortedMap.Builder<RandomAccessData, Long> builder = ImmutableSortedMap
            .orderedBy(RandomAccessData.UNSIGNED_LEXICOGRAPHICAL_COMPARATOR);

    // Read the index into memory.
    while (iterator.hasNext()) {
        KV<RandomAccessData, Long> next = iterator.next();
        builder.put(next.getKey(), next.getValue());
    }
    index = builder.build();
    return inChannel;
}