Example usage for com.google.common.collect ImmutableRangeMap.Builder put

List of usage examples for com.google.common.collect ImmutableRangeMap.Builder put

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableRangeMap.Builder put.

Prototype

@Override
    public void put(Range<K> range, V value) 

Source Link

Usage

From source file:com.github.fge.largetext.sequence.CharSequenceFactory.java

/**
 * Get an appropriate character sequence for the requested range
 *
 * <p>Depending on the requested range and window size, this will return
 * either a ({@link CharSequence#subSequence(int, int)} of a) {@link
 * CharBuffer}, a {@link MultiRangeCharSequence}, or even {@link
 * EmptyCharSequence#INSTANCE} if the requested range is empty.</p>
 *
 * @param range the requested range of characters
 * @return the appropriate {@link CharSequence}
 *///  ww  w .  j ava2 s . com
public CharSequence getSequence(final IntRange range) {
    Preconditions.checkNotNull(range, "range cannot be null");
    if (range.isEmpty())
        return EmptyCharSequence.INSTANCE;
    final List<TextRange> textRanges = decoder.getRanges(range);
    if (textRanges.size() == 1) {
        final TextRange textRange = textRanges.get(0);
        final IntRange charRange = textRange.getCharRange();
        final CharBuffer buffer = loader.load(textRange);
        final int start = range.getLowerBound() - charRange.getLowerBound();
        final int end = range.getUpperBound() - charRange.getLowerBound();
        return buffer.subSequence(start, end);
    }
    final Map<TextRange, CharBuffer> map = loader.loadAll(textRanges);
    final ImmutableRangeMap.Builder<Integer, CharBuffer> builder = ImmutableRangeMap.builder();

    for (final Map.Entry<TextRange, CharBuffer> entry : map.entrySet())
        builder.put(entry.getKey().getCharRange().asGuavaRange(), entry.getValue());

    return new MultiRangeCharSequence(this, range, builder.build());
}

From source file:org.apache.drill.exec.store.AffinityCalculator.java

/**
 * Builds a mapping of block locations to file byte range
 *//*from  ww w .j a va 2  s .c om*/
private void buildBlockMap(String fileName) {
    final Timer.Context context = metrics.timer(BLOCK_MAP_BUILDER_TIMER).time();
    BlockLocation[] blocks;
    ImmutableRangeMap<Long, BlockLocation> blockMap;
    try {
        FileStatus file = fs.getFileStatus(new Path(fileName));
        blocks = fs.getFileBlockLocations(file, 0, file.getLen());
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    ImmutableRangeMap.Builder<Long, BlockLocation> blockMapBuilder = new ImmutableRangeMap.Builder<Long, BlockLocation>();
    for (BlockLocation block : blocks) {
        long start = block.getOffset();
        long end = start + block.getLength();
        Range<Long> range = Range.closedOpen(start, end);
        blockMapBuilder = blockMapBuilder.put(range, block);
    }
    blockMap = blockMapBuilder.build();
    blockMapMap.put(fileName, blockMap);
    context.stop();
}

From source file:org.apache.drill.exec.store.schedule.BlockMapBuilder.java

/**
 * Builds a mapping of block locations to file byte range
 *//*from  w  w w.  j  ava  2s.  c  om*/
private ImmutableRangeMap<Long, BlockLocation> buildBlockMap(FileStatus status) throws IOException {
    final Timer.Context context = metrics.timer(BLOCK_MAP_BUILDER_TIMER).time();
    BlockLocation[] blocks;
    ImmutableRangeMap<Long, BlockLocation> blockMap;
    blocks = fs.getFileBlockLocations(status, 0, status.getLen());
    ImmutableRangeMap.Builder<Long, BlockLocation> blockMapBuilder = new ImmutableRangeMap.Builder<Long, BlockLocation>();
    for (BlockLocation block : blocks) {
        long start = block.getOffset();
        long end = start + block.getLength();
        Range<Long> range = Range.closedOpen(start, end);
        blockMapBuilder = blockMapBuilder.put(range, block);
    }
    blockMap = blockMapBuilder.build();
    blockMapMap.put(status.getPath(), blockMap);
    context.stop();
    return blockMap;
}

From source file:guru.qas.martini.gherkin.DefaultMixology.java

protected RangeMap<Integer, ScenarioDefinition> getRangeMap(FeatureWrapper feature) {
    List<ScenarioDefinition> children = Lists.newArrayList(feature.getChildren());

    ImmutableRangeMap.Builder<Integer, ScenarioDefinition> builder = ImmutableRangeMap.builder();
    while (!children.isEmpty()) {
        ScenarioDefinition child = children.remove(0);
        Location location = child.getLocation();
        Integer childStart = location.getLine();

        ScenarioDefinition sibling = children.isEmpty() ? null : children.get(0);
        Location siblingLocation = null == sibling ? null : sibling.getLocation();
        Integer siblingStart = null == siblingLocation ? null : siblingLocation.getLine();

        Range<Integer> range = null == siblingStart ? Range.atLeast(childStart)
                : Range.closedOpen(childStart, siblingStart);
        builder.put(range, child);
    }/* ww w. j  a v  a  2  s . c o  m*/
    return builder.build();
}

From source file:com.google.googlejavaformat.java.JavaInput.java

/**
 * Input constructor.//  w w w.  j  av a2  s .  c om
 *
 * @param text the input text
 * @throws FormatterException if the input cannot be parsed
 */
public JavaInput(String text) throws FormatterException {
    this.text = checkNotNull(text);
    setLines(ImmutableList.copyOf(Newlines.lineIterator(text)));
    ImmutableList<Tok> toks = buildToks(text);
    positionToColumnMap = makePositionToColumnMap(toks);
    tokens = buildTokens(toks);
    ImmutableRangeMap.Builder<Integer, Token> tokenLocations = ImmutableRangeMap.builder();
    for (Token token : tokens) {
        Input.Tok end = JavaOutput.endTok(token);
        int upper = end.getPosition();
        if (!end.getText().isEmpty()) {
            upper += end.length() - 1;
        }
        tokenLocations.put(Range.closed(JavaOutput.startTok(token).getPosition(), upper), token);
    }
    positionTokenMap = tokenLocations.build();

    // adjust kN for EOF
    kToToken = new Token[kN + 1];
    for (Token token : tokens) {
        for (Input.Tok tok : token.getToksBefore()) {
            if (tok.getIndex() < 0) {
                continue;
            }
            kToToken[tok.getIndex()] = token;
        }
        kToToken[token.getTok().getIndex()] = token;
        for (Input.Tok tok : token.getToksAfter()) {
            if (tok.getIndex() < 0) {
                continue;
            }
            kToToken[tok.getIndex()] = token;
        }
    }
}

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

public void refresh() {
    List<TokenRange> tokenRanges = getTokenRanges();

    ImmutableRangeMap.Builder<Token, List<InetAddress>> newTokenRing = ImmutableRangeMap.builder();
    for (TokenRange tokenRange : tokenRanges) {
        List<InetAddress> hosts = Lists.transform(tokenRange.getEndpoints(),
                new Function<String, InetAddress>() {
                    @Override//from  www. jav a  2  s.  c om
                    public InetAddress apply(String endpoint) {
                        try {
                            return InetAddress.getByName(endpoint);
                        } catch (UnknownHostException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
        Token startToken = new Token(BaseEncoding.base16().decode(tokenRange.getStart_token().toUpperCase()));
        Token endToken = new Token(BaseEncoding.base16().decode(tokenRange.getEnd_token().toUpperCase()));
        if (startToken.compareTo(endToken) <= 0) {
            newTokenRing.put(Range.openClosed(startToken, endToken), hosts);
        } else {
            // Handle wrap-around
            newTokenRing.put(Range.greaterThan(startToken), hosts);
            newTokenRing.put(Range.atMost(endToken), hosts);
        }
    }
    tokenRing.set(newTokenRing.build());
}

From source file:io.horizondb.model.core.blocks.AbstractDataBlock.java

/**
 * {@inheritDoc}/*from   www .  j  av  a 2 s  .  c o  m*/
 */
@Override
public final RangeMap<Field, DataBlock> split(TimeSeriesDefinition definition) throws IOException {

    Range<Field> range = BlockHeaderUtils.getRange(getHeader());

    Range<Field> partitionRange = definition.getPartitionTimeRange(range.lowerEndpoint());

    if (partitionRange.contains(range.upperEndpoint())) {
        return ImmutableRangeMap.<Field, DataBlock>of(partitionRange, this);
    }

    TimeSeriesRecord[] records = definition.newRecords();

    ImmutableRangeMap.Builder<Field, DataBlock> builder = ImmutableRangeMap.builder();

    RecordAppender appender = new RecordAppender(definition, Buffers.getDefaultAllocator(), records);

    Field[] timestamps = new Field[records.length];
    for (int i = 0; i < timestamps.length; i++) {
        timestamps[i] = definition.newField(Record.TIMESTAMP_FIELD_NAME);
    }

    try (BinaryTimeSeriesRecordIterator iterator = new BinaryTimeSeriesRecordIterator(definition,
            singleton(this))) {

        while (iterator.hasNext()) {

            Record record = iterator.next();
            Field timestamp = timestamps[record.getType()];
            if (record.isDelta()) {
                timestamp.add(record.getField(Record.TIMESTAMP_FIELD_INDEX));
            } else {
                record.getField(Record.TIMESTAMP_FIELD_INDEX).copyTo(timestamp);
            }

            if (!partitionRange.contains(timestamp)) {

                builder.put(partitionRange, appender.getDataBlock());
                partitionRange = definition.getPartitionTimeRange(timestamp);
                appender = new RecordAppender(definition, Buffers.getDefaultAllocator(), records);
            }
            appender.append(record);
        }
        builder.put(partitionRange, appender.getDataBlock());
    }

    return builder.build();
}

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

private void refreshTokenRanges() {
    try {//from w ww. j a  v  a 2s.  c  om
        List<TokenRange> tokenRanges = getRandomGoodHost().runWithPooledResource(describeRing);

        ImmutableRangeMap.Builder<LightweightOPPToken, List<InetSocketAddress>> newTokenRing = ImmutableRangeMap
                .builder();
        for (TokenRange tokenRange : tokenRanges) {
            List<InetSocketAddress> hosts = Lists.transform(tokenRange.getEndpoints(),
                    new Function<String, InetSocketAddress>() {
                        @Override
                        public InetSocketAddress apply(String endpoint) {
                            return new InetSocketAddress(endpoint, CassandraConstants.DEFAULT_THRIFT_PORT);
                        }
                    });
            LightweightOPPToken startToken = new LightweightOPPToken(
                    BaseEncoding.base16().decode(tokenRange.getStart_token().toUpperCase()));
            LightweightOPPToken endToken = new LightweightOPPToken(
                    BaseEncoding.base16().decode(tokenRange.getEnd_token().toUpperCase()));
            if (startToken.compareTo(endToken) <= 0) {
                newTokenRing.put(Range.openClosed(startToken, endToken), hosts);
            } else {
                // Handle wrap-around
                newTokenRing.put(Range.greaterThan(startToken), hosts);
                newTokenRing.put(Range.atMost(endToken), hosts);
            }
        }
        tokenMap = newTokenRing.build();

    } catch (Exception e) {
        log.error("Couldn't grab new token ranges for token aware cassandra mapping!", e);
    }
}