Example usage for io.netty.buffer ByteBufAllocator buffer

List of usage examples for io.netty.buffer ByteBufAllocator buffer

Introduction

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

Prototype

ByteBuf buffer(int initialCapacity);

Source Link

Document

Allocate a ByteBuf with the given initial capacity.

Usage

From source file:org.curioswitch.curiostack.gcloud.core.auth.ServiceAccountAccessTokenProvider.java

License:Open Source License

@Override
ByteBuf refreshRequestContent(Type type) {
    long currentTimeMillis = clock().millis();
    String assertion = createAssertion(type, currentTimeMillis);
    QueryStringEncoder formEncoder = new QueryStringEncoder("");
    formEncoder.addParam("grant_type", GRANT_TYPE);
    formEncoder.addParam("assertion", assertion);
    String contentWithQuestionMark = formEncoder.toString();

    ByteBufAllocator alloc = RequestContext.mapCurrent(RequestContext::alloc,
            () -> PooledByteBufAllocator.DEFAULT);
    assert alloc != null;
    ByteBuf content = alloc.buffer(contentWithQuestionMark.length() - 1);
    ByteBufUtil.writeAscii(content, contentWithQuestionMark.substring(1));
    return content;
}

From source file:org.curioswitch.curiostack.gcloud.storage.StorageClient.java

License:Open Source License

/**
 * Reads the contents of a file from cloud storage. Ownership of the returned {@link ByteBuf} is
 * transferred to the caller, which must release it. The future will complete with {@code null} if
 * the file is not found.//from  ww  w . ja  va  2  s. c o  m
 */
public CompletableFuture<ByteBuf> readFile(String filename, EventLoop eventLoop, ByteBufAllocator alloc) {
    String url = objectUrlPrefix + urlPathSegmentEscaper().escape(filename) + "?alt=media";

    return httpClient.get(url).aggregateWithPooledObjects(eventLoop, alloc).thenApply(msg -> {
        if (msg.status().equals(HttpStatus.NOT_FOUND)) {
            ReferenceCountUtil.safeRelease(msg.content());
            return null;
        }
        if (!msg.status().equals(HttpStatus.OK)) {
            String response = msg.contentUtf8();
            ReferenceCountUtil.safeRelease(msg.content());
            throw new InvalidResponseException("Could not fetch file: " + response);
        }
        HttpData data = msg.content();
        if (data instanceof ByteBufHolder) {
            return ((ByteBufHolder) msg.content()).content();
        } else {
            ByteBuf buf = alloc.buffer(data.length());
            buf.writeBytes(data.array(), data.offset(), data.length());
            return buf;
        }
    });
}

From source file:org.dcache.http.ReusableChunkedNioFile.java

License:Apache License

/**
 * Like {@link ChunkedNioFile#readChunk}, but uses position independent
 * IO calls.//from w w w .  j a va2  s  .  co m
 */
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
    long offset = _offset;
    if (offset >= _endOffset) {
        return null;
    }

    int length = (int) Math.min(_chunkSize, _endOffset - offset);
    ByteBuf chunk = allocator.buffer(length);
    boolean release = true;
    try {
        ByteBuffer buffer = chunk.nioBuffer(0, length);

        while (buffer.hasRemaining()) {
            /* use position independent thread safe call */
            int bytes = _channel.read(buffer, offset);
            if (bytes < 0) {
                break;
            }
            offset += bytes;
        }
        chunk.writerIndex(buffer.position());
        _offset = offset;
        release = false;
        return chunk;
    } finally {
        if (release) {
            chunk.release();
        }
    }
}

From source file:org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput.java

License:Open Source License

@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {

    if (!open) {/*from   ww w . j a va  2 s.c  o m*/
        return null;
    }

    ByteBuffer top = queue.poll(READ_TIMEOUT, TimeUnit.MILLISECONDS);

    if (top == null) {
        // returning empty buffer instead of null causes flush (which is needed for BroadcasterTest and others..).
        return Unpooled.EMPTY_BUFFER;
    }

    if (top == VOID) {
        open = false;
        return null;
    }

    int topRemaining = top.remaining();
    ByteBuf buffer = allocator.buffer(topRemaining);

    buffer.setBytes(0, top);
    buffer.setIndex(0, topRemaining);

    if (top.remaining() > 0) {
        queue.addFirst(top);
    }

    offset += topRemaining;

    return buffer;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodeConnectMessage(ByteBufAllocator byteBufAllocator, MqttConnectMessage message) {
    int payloadBufferSize = 0;

    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttConnectVariableHeader variableHeader = message.variableHeader();
    MqttConnectPayload payload = message.payload();
    MqttVersion mqttVersion = MqttVersion.fromProtocolNameAndLevel(variableHeader.name(),
            (byte) variableHeader.version());

    // Client id// www  .j ava 2s  .  com
    String clientIdentifier = payload.clientIdentifier();
    if (!isValidClientId(mqttVersion, clientIdentifier)) {
        throw new MqttIdentifierRejectedException("invalid clientIdentifier: " + clientIdentifier);
    }
    byte[] clientIdentifierBytes = encodeStringUtf8(clientIdentifier);
    payloadBufferSize += 2 + clientIdentifierBytes.length;

    // Will topic and message
    String willTopic = payload.willTopic();
    byte[] willTopicBytes = willTopic != null ? encodeStringUtf8(willTopic) : EmptyArrays.EMPTY_BYTES;
    String willMessage = payload.willMessage();
    byte[] willMessageBytes = willMessage != null ? encodeStringUtf8(willMessage) : EmptyArrays.EMPTY_BYTES;
    if (variableHeader.isWillFlag()) {
        payloadBufferSize += 2 + willTopicBytes.length;
        payloadBufferSize += 2 + willMessageBytes.length;
    }

    String userName = payload.userName();
    byte[] userNameBytes = userName != null ? encodeStringUtf8(userName) : EmptyArrays.EMPTY_BYTES;
    if (variableHeader.hasUserName()) {
        payloadBufferSize += 2 + userNameBytes.length;
    }

    String password = payload.password();
    byte[] passwordBytes = password != null ? encodeStringUtf8(password) : EmptyArrays.EMPTY_BYTES;
    if (variableHeader.hasPassword()) {
        payloadBufferSize += 2 + passwordBytes.length;
    }

    // Fixed header
    byte[] protocolNameBytes = mqttVersion.protocolNameBytes();
    int variableHeaderBufferSize = 2 + protocolNameBytes.length + 4;
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);
    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);

    buf.writeShort(protocolNameBytes.length);
    buf.writeBytes(protocolNameBytes);

    buf.writeByte(variableHeader.version());
    buf.writeByte(getConnVariableHeaderFlag(variableHeader));
    buf.writeShort(variableHeader.keepAliveTimeSeconds());

    // Payload
    buf.writeShort(clientIdentifierBytes.length);
    buf.writeBytes(clientIdentifierBytes, 0, clientIdentifierBytes.length);
    if (variableHeader.isWillFlag()) {
        buf.writeShort(willTopicBytes.length);
        buf.writeBytes(willTopicBytes, 0, willTopicBytes.length);
        buf.writeShort(willMessageBytes.length);
        buf.writeBytes(willMessageBytes, 0, willMessageBytes.length);
    }
    if (variableHeader.hasUserName()) {
        buf.writeShort(userNameBytes.length);
        buf.writeBytes(userNameBytes, 0, userNameBytes.length);
    }
    if (variableHeader.hasPassword()) {
        buf.writeShort(passwordBytes.length);
        buf.writeBytes(passwordBytes, 0, passwordBytes.length);
    }
    return buf;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodeConnAckMessage(ByteBufAllocator byteBufAllocator, MqttConnAckMessage message) {
    ByteBuf buf = byteBufAllocator.buffer(4);
    buf.writeByte(getFixedHeaderByte1(message.fixedHeader()));
    buf.writeByte(2);//from   w  w w. ja v  a  2  s.  com
    buf.writeByte(message.variableHeader().isSessionPresent() ? 0x01 : 0x00);
    buf.writeByte(message.variableHeader().connectReturnCode().byteValue());

    return buf;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodeSubscribeMessage(ByteBufAllocator byteBufAllocator, MqttSubscribeMessage message) {
    int variableHeaderBufferSize = 2;
    int payloadBufferSize = 0;

    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttMessageIdVariableHeader variableHeader = message.variableHeader();
    MqttSubscribePayload payload = message.payload();

    for (MqttTopicSubscription topic : payload.topicSubscriptions()) {
        String topicName = topic.topicName();
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        payloadBufferSize += 2 + topicNameBytes.length;
        payloadBufferSize += 1;/*  w w  w  . j a  v a2s  .c o  m*/
    }

    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);

    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);

    // Variable Header
    int messageId = variableHeader.messageId();
    buf.writeShort(messageId);

    // Payload
    for (MqttTopicSubscription topic : payload.topicSubscriptions()) {
        String topicName = topic.topicName();
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        buf.writeShort(topicNameBytes.length);
        buf.writeBytes(topicNameBytes, 0, topicNameBytes.length);
        buf.writeByte(topic.qualityOfService().value());
    }

    return buf;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodeUnsubscribeMessage(ByteBufAllocator byteBufAllocator,
        MqttUnsubscribeMessage message) {
    int variableHeaderBufferSize = 2;
    int payloadBufferSize = 0;

    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttMessageIdVariableHeader variableHeader = message.variableHeader();
    MqttUnsubscribePayload payload = message.payload();

    for (String topicName : payload.topics()) {
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        payloadBufferSize += 2 + topicNameBytes.length;
    }/*  w w w  .  j ava  2s .c om*/

    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);

    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);

    // Variable Header
    int messageId = variableHeader.messageId();
    buf.writeShort(messageId);

    // Payload
    for (String topicName : payload.topics()) {
        byte[] topicNameBytes = encodeStringUtf8(topicName);
        buf.writeShort(topicNameBytes.length);
        buf.writeBytes(topicNameBytes, 0, topicNameBytes.length);
    }

    return buf;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodeSubAckMessage(ByteBufAllocator byteBufAllocator, MqttSubAckMessage message) {
    int variableHeaderBufferSize = 2;
    int payloadBufferSize = message.payload().grantedQoSLevels().size();
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);
    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(message.fixedHeader()));
    writeVariableLengthInt(buf, variablePartSize);
    buf.writeShort(message.variableHeader().messageId());
    for (int qos : message.payload().grantedQoSLevels()) {
        buf.writeByte(qos);/*from   ww w . jav  a  2  s  . c  o  m*/
    }

    return buf;
}

From source file:shi.cs.MqttEncoder.java

License:Apache License

private static ByteBuf encodePublishMessage(ByteBufAllocator byteBufAllocator, MqttPublishMessage message) {
    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttPublishVariableHeader variableHeader = message.variableHeader();
    ByteBuf payload = message.payload().duplicate();

    String topicName = variableHeader.topicName();
    byte[] topicNameBytes = encodeStringUtf8(topicName);

    int variableHeaderBufferSize = 2 + topicNameBytes.length + (mqttFixedHeader.qosLevel().value() > 0 ? 2 : 0);
    int payloadBufferSize = payload.readableBytes();
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);

    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);
    buf.writeShort(topicNameBytes.length);
    buf.writeBytes(topicNameBytes);/*from www .j av  a 2 s. c o m*/
    if (mqttFixedHeader.qosLevel().value() > 0) {
        buf.writeShort(variableHeader.messageId());
    }
    buf.writeBytes(payload);

    return buf;
}