Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Returns the index in the buffer of the end of header if found.
 * Returns -1 if no end of header was found in the buffer.
 *//*from w ww .j  a  va  2  s.c  om*/
private static int findEndOfHeader(final ByteBuf buffer) {
    final int n = buffer.readableBytes();

    // per spec, the 15th and 16th bytes contain the address length in bytes
    if (n < 16) {
        return -1;
    }

    int offset = buffer.readerIndex() + 14;

    // the total header length will be a fixed 16 byte sequence + the dynamic address information block
    int totalHeaderBytes = 16 + buffer.getUnsignedShort(offset);

    // ensure we actually have the full header available
    if (n >= totalHeaderBytes) {
        return totalHeaderBytes;
    } else {
        return -1;
    }
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Returns the index in the buffer of the end of line found.
 * Returns -1 if no end of line was found in the buffer.
 *///  w  w  w.  j  a v a 2 s.c  om
private static int findEndOfLine(final ByteBuf buffer) {
    final int n = buffer.writerIndex();
    for (int i = buffer.readerIndex(); i < n; i++) {
        final byte b = buffer.getByte(i);
        if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') {
            return i; // \r\n
        }
    }
    return -1; // Not found.
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 * Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
 * @param buffer  the {@link ByteBuf} from which to read data
 * @return frame  the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                be created/*from  w w  w .  j a v  a 2 s .co  m*/
 */
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eoh = findEndOfHeader(buffer);
    if (!discarding) {
        if (eoh >= 0) {
            final int length = eoh - buffer.readerIndex();
            if (length > v2MaxHeaderSize) {
                buffer.readerIndex(eoh);
                failOverLimit(ctx, length);
                return null;
            }
            return buffer.readSlice(length);
        } else {
            final int length = buffer.readableBytes();
            if (length > v2MaxHeaderSize) {
                discardedBytes = length;
                buffer.skipBytes(length);
                discarding = true;
                failOverLimit(ctx, "over " + discardedBytes);
            }
            return null;
        }
    } else {
        if (eoh >= 0) {
            buffer.readerIndex(eoh);
            discardedBytes = 0;
            discarding = false;
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.skipBytes(discardedBytes);
        }
        return null;
    }
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 * Based on code from {@link LineBasedFrameDecoder#decode(ChannelHandlerContext, ByteBuf)}.
 *
 * @param ctx     the {@link ChannelHandlerContext} which this {@link HAProxyMessageDecoder} belongs to
 * @param buffer  the {@link ByteBuf} from which to read data
 * @return frame  the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                be created/*from w  w  w  .j a  va2s.  co  m*/
 */
private ByteBuf decodeLine(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol >= 0) {
            final int length = eol - buffer.readerIndex();
            if (length > V1_MAX_LENGTH) {
                buffer.readerIndex(eol + DELIMITER_LENGTH);
                failOverLimit(ctx, length);
                return null;
            }
            ByteBuf frame = buffer.readSlice(length);
            buffer.skipBytes(DELIMITER_LENGTH);
            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > V1_MAX_LENGTH) {
                discardedBytes = length;
                buffer.skipBytes(length);
                discarding = true;
                failOverLimit(ctx, "over " + discardedBytes);
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.skipBytes(discardedBytes);
        }
        return null;
    }
}

From source file:nl.thijsalders.spigotproxy.haproxy.HAProxyMessageDecoder.java

License:Apache License

/**
 * Returns the {@link ProtocolDetectionResult} for the given {@link ByteBuf}.
 *//*from w ww.  ja v a 2s.  c  o m*/
public static ProtocolDetectionResult<HAProxyProtocolVersion> detectProtocol(ByteBuf buffer) {
    if (buffer.readableBytes() < 12) {
        return ProtocolDetectionResult.needsMoreData();
    }

    int idx = buffer.readerIndex();

    if (match(BINARY_PREFIX, buffer, idx)) {
        return DETECTION_RESULT_V2;
    }
    if (match(TEXT_PREFIX, buffer, idx)) {
        return DETECTION_RESULT_V1;
    }
    return ProtocolDetectionResult.invalid();
}

From source file:no.nb.nna.broprox.dnsservice.DnsLookup.java

License:Apache License

protected void storeDnsRecord(final String host, final State state)
        throws IOException, NoSuchAlgorithmException, InterruptedException, StatusException {

    ByteBuf payload = Unpooled.buffer();

    // Start the record with a 14-digit date per RFC 2540
    VariablePrecisionDateTime fetchDate = new VariablePrecisionDateTime(state.fetchStart, Granularity.SECOND);
    payload.writeCharSequence(fetchDate.toFormattedString(DateFormat.HERITRIX), StandardCharsets.UTF_8);
    payload.writeByte('\n');

    for (Record r : state.answers) {
        payload.writeCharSequence(r.toString(), StandardCharsets.UTF_8);
        payload.writeByte('\n');
    }//from   ww  w  . ja  v a2s  .c om

    byte[] buf = new byte[payload.readableBytes()];
    payload.getBytes(payload.readerIndex(), buf);

    CrawlLog.Builder crawlLogBuilder = CrawlLog.newBuilder().setRecordType("response")
            .setRequestedUri("dns:" + host).setDiscoveryPath("P").setStatusCode(1)
            .setFetchTimeStamp(ProtoUtils.odtToTs(state.fetchStart)).setIpAddress(state.dnsIp)
            .setContentType("text/dns").setSize(payload.readableBytes());

    // Shall we get a digest on the content downloaded?
    if (digestContent) {
        MessageDigest digest = MessageDigest.getInstance(getDigestAlgorithm());

        String digestString = "sha1:" + new BigInteger(1, digest.digest(buf)).toString(16);
        crawlLogBuilder.setBlockDigest(digestString);
    }

    CrawlLog crawlLog = crawlLogBuilder.build();
    if (db != null) {
        crawlLog = db.addCrawlLog(crawlLog);
    }

    if (contentWriterClient != null) {
        String uri = contentWriterClient.createSession().sendCrawlLog(crawlLog)
                .sendPayload(ByteString.copyFrom(buf)).finish();
    }

    LOG.debug("DNS record for {} written", host);
}

From source file:org.apache.activemq.artemis.core.io.mapped.MappedSequentialFile.java

License:Apache License

@Override
public void write(ActiveMQBuffer bytes, boolean sync, IOCallback callback) throws IOException {
    if (callback == null) {
        throw new NullPointerException("callback parameter need to be set");
    }//  w w w . ja v  a 2s . com
    checkIsOpen(callback);
    try {
        final ByteBuf byteBuf = bytes.byteBuf();
        final int writerIndex = byteBuf.writerIndex();
        final int readerIndex = byteBuf.readerIndex();
        final int readableBytes = writerIndex - readerIndex;
        if (readableBytes > 0) {
            this.mappedFile.write(byteBuf, readerIndex, readableBytes);
            if (factory.isDatasync() && sync) {
                this.mappedFile.force();
            }
        }
        callback.done();
    } catch (IOException e) {
        if (this.criticalErrorListener != null) {
            this.criticalErrorListener.onIOException(new ActiveMQIOErrorException(e.getMessage(), e),
                    e.getMessage(), this);
        }
        callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), e.getMessage());
        throw e;
    }
}

From source file:org.apache.activemq.artemis.core.io.mapped.MappedSequentialFile.java

License:Apache License

@Override
public void write(ActiveMQBuffer bytes, boolean sync) throws IOException {
    checkIsOpen();/*from  w  w w  . jav a2  s .c om*/
    final ByteBuf byteBuf = bytes.byteBuf();
    final int writerIndex = byteBuf.writerIndex();
    final int readerIndex = byteBuf.readerIndex();
    final int readableBytes = writerIndex - readerIndex;
    if (readableBytes > 0) {
        this.mappedFile.write(byteBuf, readerIndex, readableBytes);
        if (factory.isDatasync() && sync) {
            this.mappedFile.force();
        }
    }
}

From source file:org.apache.activemq.artemis.core.message.impl.CoreMessage.java

License:Apache License

private void decodeHeadersAndProperties(final ByteBuf buffer, boolean lazyProperties) {
    messageIDPosition = buffer.readerIndex();
    messageID = buffer.readLong();/* w ww  . j a v  a 2s  .co m*/

    address = SimpleString.readNullableSimpleString(buffer,
            coreMessageObjectPools == null ? null : coreMessageObjectPools.getAddressDecoderPool());
    if (buffer.readByte() == DataConstants.NOT_NULL) {
        byte[] bytes = new byte[16];
        buffer.readBytes(bytes);
        userID = new UUID(UUID.TYPE_TIME_BASED, bytes);
    } else {
        userID = null;
    }
    type = buffer.readByte();
    durable = buffer.readBoolean();
    expiration = buffer.readLong();
    timestamp = buffer.readLong();
    priority = buffer.readByte();
    if (lazyProperties) {
        properties = null;
        propertiesLocation = buffer.readerIndex();
    } else {
        properties = new TypedProperties();
        properties.decode(buffer,
                coreMessageObjectPools == null ? null : coreMessageObjectPools.getPropertiesDecoderPools());
    }
}

From source file:org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.java

License:Apache License

protected ByteBuf copyMessageBuffer(ByteBuf buffer, int skipBytes) {

    ByteBuf newNettyBuffer = Unpooled.buffer(buffer.capacity() - PACKET_HEADERS_SIZE - skipBytes);

    int read = buffer.readerIndex();
    int writ = buffer.writerIndex();
    buffer.readerIndex(PACKET_HEADERS_SIZE);

    newNettyBuffer.writeBytes(buffer, buffer.readableBytes() - skipBytes);
    buffer.setIndex(read, writ);/*  w  w w.  j  ava2 s. c  o m*/
    newNettyBuffer.setIndex(0, writ - PACKET_HEADERS_SIZE - skipBytes);

    return newNettyBuffer;
}