Example usage for io.netty.buffer ByteBuf getLong

List of usage examples for io.netty.buffer ByteBuf getLong

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf getLong.

Prototype

public abstract long getLong(int index);

Source Link

Document

Gets a 64-bit long integer at the specified absolute index in this buffer.

Usage

From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf inBuffer) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, inBuffer.readableBytes());
        inBuffer.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(ctx, false);//w w w  . jav a  2  s  .  c o  m
        return null;
    }

    if (inBuffer.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = inBuffer.readerIndex() + lengthFieldOffset;
    long frameLength;
    switch (lengthFieldLength) {
    case 1:
        frameLength = inBuffer.getUnsignedByte(actualLengthFieldOffset);
        break;
    case 2:
        frameLength = inBuffer.getUnsignedShort(actualLengthFieldOffset);
        break;
    case 3:
        frameLength = inBuffer.getUnsignedMedium(actualLengthFieldOffset);
        break;
    case 4:
        frameLength = ByteBufUtil.swapInt((int) inBuffer.getUnsignedInt(actualLengthFieldOffset)); //SWAP FOR UIMANAGER
        break;
    case 8:
        frameLength = inBuffer.getLong(actualLengthFieldOffset);
        break;
    default:
        throw new Error("should not reach here");
    }

    if (frameLength < 0) {
        inBuffer.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        inBuffer.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - inBuffer.readableBytes();
        inBuffer.skipBytes(inBuffer.readableBytes());
        failIfNecessary(ctx, true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (inBuffer.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        inBuffer.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    inBuffer.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = inBuffer.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(inBuffer, readerIndex, actualFrameLength);
    inBuffer.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.celeral.netlet.benchmark.netty.BenchmarkTcpClient.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;
    long timestamp = byteBuf.getLong(0);
    byteBuf.release();//  w w w. j  a  v  a2s.  com

    if (timestamp < -2) {
        logger.error("Received bad timestamp {}", timestamp);
        ctx.close();
        return;
    } else if (timestamp != this.timestamp) {
        logger.error("Received bad timestamp {}. Sent timestamp {}", timestamp, this.timestamp);
        ctx.close();
        return;
    } else if (timestamp > 0) {
        benchmarkResults.addResult(System.nanoTime() - timestamp);
    }
    send(ctx);
}

From source file:com.celeral.netlet.benchmark.netty.EchoTcpServer.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf byteBuf = (ByteBuf) msg;

    long timestamp = byteBuf.getLong(0);

    if (timestamp > 0) {
        benchmarkResults.addResult(System.nanoTime() - timestamp);
    } else if (timestamp == -1) {
        start = System.currentTimeMillis();
        logger.info("Received the first message.");
    } else if (timestamp == -2) {
        logger.info("Finished receiving messages! Overall test time: {} millis",
                System.currentTimeMillis() - start);
        ctx.close();//from   ww  w.  j  av a  2  s. c om
        benchmarkResults.printResults(System.out);
        return;
    } else if (timestamp < 0) {
        logger.error("Received bad timestamp {}", timestamp);
        ctx.close();
        return;
    }

    ctx.writeAndFlush(msg);
}

From source file:com.chat.common.netty.handler.decode.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 * decode the length field encoded differently.  Note that this method must not modify the state of the specified
 * buffer (e.g. {@code readerIndex}, {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException if failed to decode the specified region
 *//* ww  w  .  ja v  a 2  s.  c o m*/
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    long frameLength;
    switch (length) {
    case 1:
        frameLength = buf.getUnsignedByte(offset);
        break;
    case 2:
        frameLength = buf.getUnsignedShort(offset);
        break;
    case 3:
        frameLength = buf.getUnsignedMedium(offset);
        break;
    case 4:
        frameLength = buf.getUnsignedInt(offset);
        break;
    case 8:
        frameLength = buf.getLong(offset);
        break;
    default:
        throw new DecoderException(
                "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
    }
    return frameLength;
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueHandler.java

License:Apache License

/**
 * Helper method to decode all other response messages.
 *
 * @param request the current request./*  w w w.  j  a  v a 2s .c  o m*/
 * @param msg the current response message.
 * @param status the response status code.
 * @return the decoded response or null if none did match.
 */
private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request,
        FullBinaryMemcacheResponse msg, ResponseStatus status, boolean seqOnMutation, String remoteHostname) {
    CouchbaseResponse response = null;
    ByteBuf content = msg.content();
    long cas = msg.getCAS();
    short statusCode = msg.getStatus();
    String bucket = request.bucket();

    if (request instanceof UnlockRequest) {
        response = new UnlockResponse(status, statusCode, bucket, content, request);
    } else if (request instanceof TouchRequest) {
        response = new TouchResponse(status, statusCode, bucket, content, request);
    } else if (request instanceof AppendRequest) {
        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request);
    } else if (request instanceof PrependRequest) {
        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request);
    } else if (request instanceof KeepAliveRequest) {
        releaseContent(content);
        response = new KeepAliveResponse(status, statusCode, request);
    } else if (request instanceof CounterRequest) {
        long value = status.isSuccess() ? content.readLong() : 0;
        releaseContent(content);

        MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(),
                request.partition());
        response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request);
    } else if (request instanceof StatRequest) {
        String key = new String(msg.getKey(), CHARSET);
        String value = content.toString(CHARSET);
        releaseContent(content);

        response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request);
    } else if (request instanceof GetAllMutationTokensRequest) {
        // 2 bytes for partition ID, and 8 bytes for sequence number
        MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10];
        for (int i = 0; i < mutationTokens.length; i++) {
            mutationTokens[i] = new MutationToken((long) content.readShort(), 0, content.readLong(),
                    request.bucket());
        }
        releaseContent(content);
        response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request);
    } else if (request instanceof ObserveRequest) {
        byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value();
        long observedCas = 0;
        if (status.isSuccess()) {
            short keyLength = content.getShort(2);
            observed = content.getByte(keyLength + 4);
            observedCas = content.getLong(keyLength + 5);
        }
        releaseContent(content);
        response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(),
                observedCas, bucket, request);
    } else if (request instanceof ObserveSeqnoRequest) {
        if (status.isSuccess()) {
            byte format = content.readByte();
            switch (format) {
            case 0:
                response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(),
                        content.readShort(), content.readLong(), content.readLong(), content.readLong(), status,
                        statusCode, bucket, request);
                break;
            case 1:
                response = new FailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(),
                        content.readShort(), content.readLong(), content.readLong(), content.readLong(),
                        content.readLong(), content.readLong(), status, statusCode, bucket, request);
                break;
            default:
                throw new IllegalStateException("Unknown format for observe-seq: " + format);
            }
        } else {
            response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0,
                    0, 0, 0, status, statusCode, bucket, request);
        }
        releaseContent(content);
    }

    return response;
}

From source file:com.github.mrstampy.kitchensync.stream.header.SequenceHeader.java

License:Open Source License

private void setSequence(byte[] seqBytes) {
    ByteBuf seq = Unpooled.copiedBuffer(seqBytes);

    sequence = seq.getLong(0);
}

From source file:com.github.mrstampy.pprspray.core.streamer.util.MediaStreamerUtils.java

License:Open Source License

/**
 * Gets the long chunk.//from w  w w.ja v  a2s  .c  o m
 *
 * @param chunk
 *          the chunk
 * @return the long chunk
 */
protected static long getLongChunk(byte[] chunk) {
    ByteBuf buf = Unpooled.copiedBuffer(chunk);

    return buf.getLong(0);
}

From source file:com.hazelcast.simulator.protocol.core.ResponseCodec.java

License:Open Source License

public static long getMessageId(ByteBuf in) {
    return in.getLong(OFFSET_MESSAGE_ID);
}

From source file:com.heliosapm.streams.metrics.aggregation.StreamedMetricAggregation.java

License:Apache License

/**
 * Creates a new StreamedMetricAggregation from the passed bytes
 * @param bytes The bytes to read from//  w w  w  .j av a2 s  .  com
 */
private StreamedMetricAggregation(final byte[] bytes) {
    size = bytes.length;
    final ByteBuf b = BufferManager.getInstance().buffer(size).writeBytes(bytes);
    try {
        sticky = b.getByte(STICKY) == 1;
        doubleType = b.getByte(DOUBLE_TYPE) == 1;
        createTime = b.getLong(CREATE_TIME);
        period = b.getLong(PERIOD);
        periodUnit = TUNITS[b.getByte(PERIOD_UNIT)];
        b.readerIndex(METRIC_VALUES);
        values.put(bytes, METRIC_VALUES, VALUE_SIZE);
        final byte tagCount = b.getByte(TAG_COUNT);
        b.readerIndex(METRIC_NAME);
        metricName = nextString(b);
        for (int i = 0; i < tagCount; i++) {
            tags.put(nextString(b), nextString(b));
            i++;
        }
    } finally {
        try {
            b.release();
        } catch (Exception x) {
            /* No Op */}
    }
}

From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java

License:Apache License

/**
 * Extracts the timestamp from a byte buff
 * @param buff the buff to extract from/*w  w w.j av  a 2  s  . c om*/
 * @return the timestamp
 */
public static long timestamp(final ByteBuf buff) {
    return buff.getLong(2);
}