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:edu.mit.streamjit.util.bytecode.methodhandles.Combinators.java

/**
 * Returns a method handle with a leading int argument that selects one of
 * the method handles in the given array, which is invoked with the
 * remaining arguments. Modifications to the array after this method returns
 * do not affect the behavior of the returned handle.
 * @param cases the switch cases// w  w w.j  a va2 s  .c  om
 * @return a method handle approximating the switch statement
 * @see #tableswitch(java.lang.invoke.MethodHandle[])
 */
public static MethodHandle lookupswitch(MethodHandle[] cases) {
    ImmutableSortedMap.Builder<Integer, MethodHandle> casesMap = ImmutableSortedMap.naturalOrder();
    for (int i = 0; i < cases.length; ++i)
        casesMap.put(i, cases[i]);
    return lookupswitch(casesMap.build());
}

From source file:ru.org.linux.search.SearchController.java

private Map<Integer, String> buildSectionFacet(FacetField sectionFacet) throws SectionNotFoundException {
    ImmutableMap.Builder<Integer, String> builder = ImmutableSortedMap.naturalOrder();

    int totalCount = 0;

    for (FacetField.Count count : sectionFacet.getValues()) {
        int sectionId = Integer.parseInt(count.getName());

        String name = sectionStore.getSection(sectionId).getName().toLowerCase();

        builder.put(sectionId, name + " (" + count.getCount() + ')');

        totalCount += count.getCount();/*from   w  w  w  . jav a2 s.c o m*/
    }

    builder.put(0, "? (" + Integer.toString(totalCount) + ')');

    return builder.build();
}

From source file:org.apache.accumulo.core.metadata.schema.TabletMetadata.java

static TabletMetadata convertRow(Iterator<Entry<Key, Value>> rowIter, EnumSet<FetchedColumns> fetchedColumns,
        boolean buildKeyValueMap) {
    Objects.requireNonNull(rowIter);

    TabletMetadata te = new TabletMetadata();
    ImmutableSortedMap.Builder<Key, Value> kvBuilder = null;
    if (buildKeyValueMap) {
        kvBuilder = ImmutableSortedMap.naturalOrder();
    }//from  w  w w . j  av a2  s.  c o  m

    ImmutableMap.Builder<String, DataFileValue> filesBuilder = ImmutableMap.builder();
    Builder<String> scansBuilder = ImmutableList.builder();
    Builder<LogEntry> logsBuilder = ImmutableList.builder();
    final ImmutableSet.Builder<String> loadedFilesBuilder = ImmutableSet.builder();
    ByteSequence row = null;

    while (rowIter.hasNext()) {
        Entry<Key, Value> kv = rowIter.next();
        Key key = kv.getKey();
        String val = kv.getValue().toString();
        String fam = key.getColumnFamilyData().toString();
        String qual = key.getColumnQualifierData().toString();

        if (buildKeyValueMap) {
            kvBuilder.put(key, kv.getValue());
        }

        if (row == null) {
            row = key.getRowData();
            KeyExtent ke = new KeyExtent(key.getRow(), (Text) null);
            te.endRow = ke.getEndRow();
            te.tableId = ke.getTableId();
        } else if (!row.equals(key.getRowData())) {
            throw new IllegalArgumentException(
                    "Input contains more than one row : " + row + " " + key.getRowData());
        }

        switch (fam.toString()) {
        case TabletColumnFamily.STR_NAME:
            if (PREV_ROW_QUAL.equals(qual)) {
                te.prevEndRow = KeyExtent.decodePrevEndRow(kv.getValue());
                te.sawPrevEndRow = true;
            }
            break;
        case ServerColumnFamily.STR_NAME:
            switch (qual) {
            case DIRECTORY_QUAL:
                te.dir = val;
                break;
            case TIME_QUAL:
                te.time = val;
                break;
            case FLUSH_QUAL:
                te.flush = OptionalLong.of(Long.parseLong(val));
                break;
            case COMPACT_QUAL:
                te.compact = OptionalLong.of(Long.parseLong(val));
                break;
            }
            break;
        case DataFileColumnFamily.STR_NAME:
            filesBuilder.put(qual, new DataFileValue(val));
            break;
        case BulkFileColumnFamily.STR_NAME:
            loadedFilesBuilder.add(qual);
            break;
        case CurrentLocationColumnFamily.STR_NAME:
            te.setLocationOnce(val, qual, LocationType.CURRENT);
            break;
        case FutureLocationColumnFamily.STR_NAME:
            te.setLocationOnce(val, qual, LocationType.FUTURE);
            break;
        case LastLocationColumnFamily.STR_NAME:
            te.last = new Location(val, qual, LocationType.LAST);
            break;
        case ScanFileColumnFamily.STR_NAME:
            scansBuilder.add(qual);
            break;
        case ClonedColumnFamily.STR_NAME:
            te.cloned = val;
            break;
        case LogColumnFamily.STR_NAME:
            logsBuilder.add(LogEntry.fromKeyValue(key, val));
            break;
        default:
            throw new IllegalStateException("Unexpected family " + fam);
        }
    }

    te.files = filesBuilder.build();
    te.loadedFiles = loadedFilesBuilder.build();
    te.fetchedCols = fetchedColumns;
    te.scans = scansBuilder.build();
    te.logs = logsBuilder.build();
    if (buildKeyValueMap) {
        te.keyValues = kvBuilder.build();
    }
    return te;
}

From source file:se.sics.caracaldb.paxos.PaxosSerializer.java

private PaxosMsg paxosFromBinary(MessageFields fields, ByteBuf buf) {
    int ballot = buf.readInt();
    byte type = buf.readByte();
    View v;/* w w w.j  a  v a  2  s . com*/
    Instance ins;
    int size;
    switch (type) {
    case PREPARE:
        return new Prepare(fields.src, fields.dst, ballot);
    case PROMISE:
        size = buf.readInt();
        ImmutableSet.Builder<Instance> builder = ImmutableSet.builder();
        for (int i = 0; i < size; i++) {
            builder.add(instanceFromBinary(buf));
        }
        v = CustomSerialisers.deserialiseView(buf);
        return new Promise(fields.src, fields.dst, ballot, builder.build(), v);
    case NO_PROMISE:
        return new NoPromise(fields.src, fields.dst, ballot);
    case ACCEPT:
        ins = instanceFromBinary(buf);
        return new Accept(fields.src, fields.dst, ballot, ins);
    case ACCEPTED:
        ins = instanceFromBinary(buf);
        v = CustomSerialisers.deserialiseView(buf);
        return new Accepted(fields.src, fields.dst, ballot, ins, v);
    case REJECTED:
        ins = instanceFromBinary(buf);
        return new Rejected(fields.src, fields.dst, ballot, ins);
    case INSTALL:
        Reconfigure rec = (Reconfigure) Serializers.fromBinary(buf, Optional.absent());
        long highestDecided = buf.readLong();
        size = buf.readInt();
        ImmutableSortedMap.Builder<Long, Value> mBuilder = ImmutableSortedMap.naturalOrder();
        for (int i = 0; i < size; i++) {
            long k = buf.readLong();
            Value val = (Value) Serializers.fromBinary(buf, Optional.absent());
            mBuilder.put(k, val);
        }
        return new Install(fields.src, fields.dst, ballot, rec, highestDecided, mBuilder.build());
    default:
        LOG.error("Unknown PaxosMsg type: {}", type);
        return null;
    }
}

From source file:org.kairosdb.datastore.cassandra.CassandraDatastore.java

@Inject
public CassandraDatastore(@Named("HOSTNAME") final String hostname,
        CassandraConfiguration cassandraConfiguration, HectorConfiguration configuration,
        KairosDataPointFactory kairosDataPointFactory) throws DatastoreException {
    try {//from   ww w  . j  a  v  a2 s .  co  m
        m_cassandraConfiguration = cassandraConfiguration;
        m_singleRowReadSize = m_cassandraConfiguration.getSingleRowReadSize();
        m_multiRowSize = m_cassandraConfiguration.getMultiRowSize();
        m_multiRowReadSize = m_cassandraConfiguration.getMultiRowReadSize();
        m_kairosDataPointFactory = kairosDataPointFactory;
        m_keyspaceName = m_cassandraConfiguration.getKeyspaceName();

        m_rowKeyCache = new DataCache<DataPointsRowKey>(m_cassandraConfiguration.getRowKeyCacheSize());
        m_metricNameCache = new DataCache<String>(m_cassandraConfiguration.getStringCacheSize());
        m_tagNameCache = new DataCache<String>(m_cassandraConfiguration.getStringCacheSize());
        m_tagValueCache = new DataCache<String>(m_cassandraConfiguration.getStringCacheSize());

        CassandraHostConfigurator hostConfig = configuration.getConfiguration();
        int threadCount = hostConfig.buildCassandraHosts().length + 3;

        m_cluster = HFactory.getOrCreateCluster("kairosdb-cluster", hostConfig,
                m_cassandraConfiguration.getCassandraAuthentication());

        KeyspaceDefinition keyspaceDef = m_cluster.describeKeyspace(m_keyspaceName);

        if (keyspaceDef == null)
            createSchema(m_cassandraConfiguration.getReplicationFactor());
        //set global consistency level
        ConfigurableConsistencyLevel confConsLevel = new ConfigurableConsistencyLevel();
        confConsLevel
                .setDefaultReadConsistencyLevel(m_cassandraConfiguration.getDataReadLevel().getHectorLevel());
        confConsLevel
                .setDefaultWriteConsistencyLevel(m_cassandraConfiguration.getDataWriteLevel().getHectorLevel());

        //create keyspace instance with specified consistency
        m_keyspace = HFactory.createKeyspace(m_keyspaceName, m_cluster, confConsLevel);

        ReentrantLock mutatorLock = new ReentrantLock();
        Condition lockCondition = mutatorLock.newCondition();

        m_dataPointWriteBuffer = new WriteBuffer<DataPointsRowKey, Integer, byte[]>(m_keyspace, CF_DATA_POINTS,
                m_cassandraConfiguration.getWriteDelay(), m_cassandraConfiguration.getMaxWriteSize(),
                DATA_POINTS_ROW_KEY_SERIALIZER, IntegerSerializer.get(), BytesArraySerializer.get(),
                new WriteBufferStats() {
                    private ImmutableSortedMap m_tags;
                    {
                        m_tags = ImmutableSortedMap.naturalOrder().put("host", hostname)
                                .put("buffer", CF_DATA_POINTS).build();
                    }

                    @Override
                    public void saveWriteSize(int pendingWrites) {
                        putInternalDataPoint("kairosdb.datastore.write_size", m_tags, m_longDataPointFactory
                                .createDataPoint(System.currentTimeMillis(), pendingWrites));
                    }
                }, mutatorLock, lockCondition, threadCount);

        m_rowKeyWriteBuffer = new WriteBuffer<String, DataPointsRowKey, String>(m_keyspace, CF_ROW_KEY_INDEX,
                m_cassandraConfiguration.getWriteDelay(), m_cassandraConfiguration.getMaxWriteSize(),
                StringSerializer.get(), DATA_POINTS_ROW_KEY_SERIALIZER, StringSerializer.get(),
                new WriteBufferStats() {
                    private ImmutableSortedMap m_tags;
                    {
                        m_tags = ImmutableSortedMap.naturalOrder().put("host", hostname)
                                .put("buffer", CF_ROW_KEY_INDEX).build();
                    }

                    @Override
                    public void saveWriteSize(int pendingWrites) {
                        putInternalDataPoint("kairosdb.datastore.write_size", m_tags, m_longDataPointFactory
                                .createDataPoint(System.currentTimeMillis(), pendingWrites));
                    }
                }, mutatorLock, lockCondition, threadCount);

        m_stringIndexWriteBuffer = new WriteBuffer<String, String, String>(m_keyspace, CF_STRING_INDEX,
                m_cassandraConfiguration.getWriteDelay(), m_cassandraConfiguration.getMaxWriteSize(),
                StringSerializer.get(), StringSerializer.get(), StringSerializer.get(), new WriteBufferStats() {
                    private ImmutableSortedMap m_tags;
                    {
                        m_tags = ImmutableSortedMap.naturalOrder().put("host", hostname)
                                .put("buffer", CF_STRING_INDEX).build();
                    }

                    @Override
                    public void saveWriteSize(int pendingWrites) {
                        putInternalDataPoint("kairosdb.datastore.write_size", m_tags, m_longDataPointFactory
                                .createDataPoint(System.currentTimeMillis(), pendingWrites));
                    }
                }, mutatorLock, lockCondition, threadCount);
    } catch (HectorException e) {
        throw new DatastoreException(e);
    }
}

From source file:com.facebook.buck.haskell.HaskellLibraryDescription.java

private HaskellPackageRule createPackage(BuildTarget target, BuildRuleParams baseParams,
        BuildRuleResolver resolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CxxPlatform cxxPlatform, Arg args, Linker.LinkableDepType depType) throws NoSuchBuildTargetException {

    BuildRule library;/*w w w.ja  va2  s . c o m*/
    switch (depType) {
    case SHARED:
        library = requireSharedLibrary(getBaseBuildTarget(target), baseParams, resolver, pathResolver,
                ruleFinder, cxxPlatform, args);
        break;
    case STATIC:
    case STATIC_PIC:
        library = requireStaticLibrary(getBaseBuildTarget(target), baseParams, resolver, pathResolver,
                ruleFinder, cxxPlatform, args, depType);
        break;
    default:
        throw new IllegalStateException();
    }

    ImmutableSortedMap.Builder<String, HaskellPackage> depPackagesBuilder = ImmutableSortedMap.naturalOrder();
    for (BuildRule rule : baseParams.getDeclaredDeps().get()) {
        if (rule instanceof HaskellCompileDep) {
            ImmutableList<HaskellPackage> packages = ((HaskellCompileDep) rule)
                    .getCompileInput(cxxPlatform, depType).getPackages();
            for (HaskellPackage pkg : packages) {
                depPackagesBuilder.put(pkg.getInfo().getIdentifier(), pkg);
            }
        }
    }
    ImmutableSortedMap<String, HaskellPackage> depPackages = depPackagesBuilder.build();

    HaskellCompileRule compileRule = requireCompileRule(baseParams, resolver, pathResolver, ruleFinder,
            cxxPlatform, args, depType);

    return HaskellPackageRule.from(target, baseParams, pathResolver, ruleFinder,
            haskellConfig.getPackager().resolve(resolver), haskellConfig.getHaskellVersion(),
            getPackageInfo(target), depPackages, compileRule.getModules(),
            ImmutableSortedSet.of(new BuildTargetSourcePath(library.getBuildTarget())),
            ImmutableSortedSet.of(compileRule.getInterfaces()));
}

From source file:ru.org.linux.search.SearchController.java

private Map<Integer, String> buildGroupFacet(int sectionId, FacetField groupFacet) throws BadGroupException {
    ImmutableMap.Builder<Integer, String> builder = ImmutableSortedMap.naturalOrder();

    int totalCount = 0;

    for (FacetField.Count count : groupFacet.getValues()) {
        int groupId = Integer.parseInt(count.getName());

        Group group = groupDao.getGroup(groupId);

        if (group.getSectionId() != sectionId) {
            continue;
        }//from w w w .j a  v a 2 s.com

        String name = group.getTitle().toLowerCase();

        builder.put(groupId, name + " (" + count.getCount() + ')');

        totalCount += count.getCount();
    }

    builder.put(0, "? (" + Integer.toString(totalCount) + ')');

    ImmutableMap<Integer, String> r = builder.build();

    if (r.size() <= 2) {
        return null;
    } else {
        return r;
    }
}

From source file:se.sics.caracaldb.global.DefaultPolicy.java

private ImmutableSortedMap<Integer, Address> getIdsForFails(LUTWorkingBuffer lut, ImmutableSet<Address> fails) {
    Set<Address> remaining = new HashSet<Address>(fails);
    ImmutableSortedMap.Builder<Integer, Address> ids = ImmutableSortedMap.naturalOrder();
    if (remaining.isEmpty()) {
        return ids.build();
    }//from ww w  .ja va  2  s .c  om
    int index = 0;
    for (Address addr : lut.hosts()) {
        if (remaining.remove(addr)) {
            ids.put(index, addr);
            if (remaining.isEmpty()) {
                break;
            }
        }
        index++;
    }
    return ids.build();
}

From source file:com.facebook.buck.core.build.engine.buildinfo.DefaultOnDiskBuildInfo.java

@Override
public void writeOutputHashes(FileHashCache fileHashCache) throws IOException {
    ImmutableSortedSet<Path> pathsForArtifact = getPathsForArtifact();

    // Grab and record the output hashes in the build metadata so that cache hits avoid re-hashing
    // file contents.  Since we use output hashes for input-based rule keys and for detecting
    // non-determinism, we would spend a lot of time re-hashing output paths -- potentially in
    // serialized in a single step. So, do the hashing here to distribute the workload across
    // several threads and cache the results.
    ImmutableSortedMap.Builder<String, String> outputHashes = ImmutableSortedMap.naturalOrder();
    Hasher hasher = Hashing.sha1().newHasher();
    for (Path path : pathsForArtifact) {
        String pathString = path.toString();
        HashCode fileHash = fileHashCache.get(projectFilesystem, path);
        hasher.putBytes(pathString.getBytes(Charsets.UTF_8));
        hasher.putBytes(fileHash.asBytes());
        outputHashes.put(pathString, fileHash.toString());
    }/*from w w  w.  j av a 2 s.com*/

    projectFilesystem.writeContentsToPath(ObjectMappers.WRITER.writeValueAsString(outputHashes.build()),
            metadataDirectory.resolve(BuildInfo.MetadataKey.RECORDED_PATH_HASHES));

    projectFilesystem.writeContentsToPath(hasher.hash().toString(),
            metadataDirectory.resolve(BuildInfo.MetadataKey.OUTPUT_HASH));
}

From source file:com.facebook.buck.cli.AuditActionGraphCommand.java

private static ImmutableSortedMap<String, String> getNodeAttributes(BuildRule rule) {
    ImmutableSortedMap.Builder<String, String> attrs = ImmutableSortedMap.naturalOrder();
    attrs.put("short_name", rule.getBuildTarget().getShortName());
    attrs.put("type", rule.getType());
    attrs.put("output", rule.getSourcePathToOutput() == null ? "" : rule.getSourcePathToOutput().toString());
    attrs.put("cacheable", rule.isCacheable() ? "true" : "false");
    attrs.put("flavored", rule.getBuildTarget().isFlavored() ? "true" : "false");
    return attrs.build();
}