Example usage for io.netty.buffer Unpooled buffer

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

Introduction

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

Prototype

public static ByteBuf buffer(int initialCapacity) 

Source Link

Document

Creates a new big-endian Java heap buffer with the specified capacity , which expands its capacity boundlessly on demand.

Usage

From source file:com.twitter.http2.HttpFrameEncoder.java

License:Apache License

/**
 * Encode an HTTP/2 WINDOW_UPDATE Frame//from  www  .  ja  v a  2  s . c o  m
 */
public ByteBuf encodeWindowUpdateFrame(int streamId, int windowSizeIncrement) {
    int length = 4;
    byte flags = 0;
    ByteBuf frame = Unpooled.buffer(HTTP_FRAME_HEADER_SIZE + length);
    writeFrameHeader(frame, length, HTTP_WINDOW_UPDATE_FRAME, flags, streamId);
    frame.writeInt(windowSizeIncrement);
    return frame;
}

From source file:com.twitter.http2.HttpFrameEncoderTest.java

License:Apache License

@Test
public void testHttpDataFrame() throws Exception {
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    ByteBuf data = Unpooled.buffer(1024);
    for (int i = 0; i < 256; i++) {
        data.writeInt(RANDOM.nextInt());
    }//w  w  w  . ja v  a  2s .c  o m
    ByteBuf frame = releaseLater(ENCODER.encodeDataFrame(streamId, false, data.duplicate()));
    assertDataFrame(frame, streamId, false, data);
}

From source file:com.twitter.http2.HttpFrameEncoderTest.java

License:Apache License

@Test
public void testHttpHeadersFrame() throws Exception {
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    boolean exclusive = RANDOM.nextBoolean();
    int dependency = RANDOM.nextInt() & 0x7FFFFFFF;
    int weight = (RANDOM.nextInt() & 0xFF) + 1;
    ByteBuf headerBlock = Unpooled.buffer(1024);
    for (int i = 0; i < 256; i++) {
        headerBlock.writeInt(RANDOM.nextInt());
    }//from   w  w w  .  j  a v a 2 s. c  om
    ByteBuf frame = releaseLater(ENCODER.encodeHeadersFrame(streamId, false, exclusive, dependency, weight,
            headerBlock.duplicate()));
    assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock);
}

From source file:com.twitter.http2.HttpFrameEncoderTest.java

License:Apache License

@Test
public void testContinuedHttpHeadersFrame() throws Exception {
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    boolean exclusive = RANDOM.nextBoolean();
    int dependency = RANDOM.nextInt() & 0x7FFFFFFF;
    int weight = (RANDOM.nextInt() & 0xFF) + 1;
    ByteBuf headerBlock = Unpooled.buffer(2 * HTTP_MAX_LENGTH);
    for (int i = 0; i < 2 * HTTP_MAX_LENGTH; i++) {
        headerBlock.writeByte(RANDOM.nextInt());
    }/*from   w ww .  j  a v a 2 s.  c  o  m*/
    ByteBuf frame = releaseLater(ENCODER.encodeHeadersFrame(streamId, false, exclusive, dependency, weight,
            headerBlock.duplicate()));
    assertHeadersFrame(frame, streamId, exclusive, dependency, weight, false, headerBlock);
}

From source file:com.twitter.http2.HttpFrameEncoderTest.java

License:Apache License

@Test
public void testHttpPushPromiseFrame() throws Exception {
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    int promisedStreamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    ByteBuf headerBlock = Unpooled.buffer(1024);
    for (int i = 0; i < 256; i++) {
        headerBlock.writeInt(RANDOM.nextInt());
    }/*from w  w w. j  ava2  s . co m*/
    ByteBuf frame = releaseLater(
            ENCODER.encodePushPromiseFrame(streamId, promisedStreamId, headerBlock.duplicate()));
    assertPushPromiseFrame(frame, streamId, promisedStreamId, headerBlock);
}

From source file:com.twitter.http2.HttpFrameEncoderTest.java

License:Apache License

@Test
public void testContinuedHttpPushPromiseFrame() throws Exception {
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    int promisedStreamId = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;
    ByteBuf headerBlock = Unpooled.buffer(2 * HTTP_MAX_LENGTH);
    for (int i = 0; i < 2 * HTTP_MAX_LENGTH; i++) {
        headerBlock.writeByte(RANDOM.nextInt());
    }//ww w . j ava2 s. c om
    ByteBuf frame = releaseLater(
            ENCODER.encodePushPromiseFrame(streamId, promisedStreamId, headerBlock.duplicate()));
    assertPushPromiseFrame(frame, streamId, promisedStreamId, headerBlock);
}

From source file:com.twitter.http2.HttpHeaderBlockDecoder.java

License:Apache License

public void decode(ByteBuf headerBlock, final HttpHeaderBlockFrame frame) throws IOException {
    HeaderListener headerListener = NULL_HEADER_LISTENER;
    if (frame != null) {
        headerListener = new HeaderListenerImpl(frame.headers());
    }/*from   ww  w  . ja v  a2 s  . c  o  m*/

    if (cumulation == null) {
        decoder.decode(new ByteBufInputStream(headerBlock), headerListener);
        if (headerBlock.isReadable()) {
            cumulation = Unpooled.buffer(headerBlock.readableBytes());
            cumulation.writeBytes(headerBlock);
        }
    } else {
        cumulation.writeBytes(headerBlock);
        decoder.decode(new ByteBufInputStream(cumulation), headerListener);
        if (cumulation.isReadable()) {
            cumulation.discardReadBytes();
        } else {
            cumulation.release();
            cumulation = null;
        }
    }
}

From source file:com.vmware.xenon.common.http.netty.NettyFullHttpRequest.java

License:Open Source License

private FullHttpRequest copy(boolean copyContent, ByteBuf newContent) {
    NettyFullHttpRequest copy = new NettyFullHttpRequest(protocolVersion(), method(), uri(),
            copyContent ? content().copy() : newContent == null ? Unpooled.buffer(0) : newContent, false);
    copy.headers().set(headers());/*from   www.jav  a 2  s . c  o  m*/
    copy.trailingHeaders().set(trailingHeaders());
    return copy;
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpServiceClient.java

License:Open Source License

private void doSendRequest(Operation op) {
    final Object originalBody = op.getBodyRaw();
    try {/*from w  w  w . j  a  v a  2s.c o m*/
        byte[] body = Utils.encodeBody(op);
        if (op.getContentLength() > getRequestPayloadSizeLimit()) {
            stopTracking(op);
            Exception e = new IllegalArgumentException("Content-Length " + op.getContentLength()
                    + " is greater than max size allowed " + getRequestPayloadSizeLimit());
            op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST));
            op.fail(e);
            return;
        }

        String pathAndQuery;
        String path = op.getUri().getPath();
        String query = op.getUri().getRawQuery();
        String userInfo = op.getUri().getRawUserInfo();
        path = path == null || path.isEmpty() ? "/" : path;
        if (query != null) {
            pathAndQuery = path + "?" + query;
        } else {
            pathAndQuery = path;
        }

        /**
         * NOTE: Pay close attention to calls that access the operation request headers, since
         * they will cause a memory allocation. We avoid the allocation by first checking if
         * the operation has any custom headers to begin with, then we check for the specific
         * header
         */
        boolean hasRequestHeaders = op.hasRequestHeaders();
        boolean useHttp2 = op.isConnectionSharing();
        if (this.httpProxy != null || useHttp2 || userInfo != null) {
            pathAndQuery = op.getUri().toString();
        }

        NettyFullHttpRequest request = null;
        HttpMethod method = HttpMethod.valueOf(op.getAction().toString());
        if (body == null || body.length == 0) {
            request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, Unpooled.buffer(0),
                    false);
        } else {
            ByteBuf content = Unpooled.wrappedBuffer(body, 0, (int) op.getContentLength());
            request = new NettyFullHttpRequest(HttpVersion.HTTP_1_1, method, pathAndQuery, content, false);
        }

        if (useHttp2) {
            // when operation is cloned, it may contain original streamId header. remove it.
            if (hasRequestHeaders) {
                op.getRequestHeaders().remove(Operation.STREAM_ID_HEADER);
            }
            // We set the operation so that once a streamId is assigned, we can record
            // the correspondence between the streamId and operation: this will let us
            // handle responses properly later.
            request.setOperation(op);

        }

        String pragmaHeader = op.getRequestHeader(Operation.PRAGMA_HEADER);

        if (op.isFromReplication() && pragmaHeader == null) {
            request.headers().set(HttpHeaderNames.PRAGMA, Operation.PRAGMA_DIRECTIVE_REPLICATED);
        }

        if (op.getTransactionId() != null) {
            request.headers().set(Operation.TRANSACTION_ID_HEADER, op.getTransactionId());
        }

        if (op.getContextId() != null) {
            request.headers().set(Operation.CONTEXT_ID_HEADER, op.getContextId());
        }

        AuthorizationContext ctx = op.getAuthorizationContext();
        if (ctx != null && ctx.getToken() != null) {
            request.headers().set(Operation.REQUEST_AUTH_TOKEN_HEADER, ctx.getToken());
        }

        boolean isXenonToXenon = op.isFromReplication();
        boolean isRequestWithCallback = false;
        if (hasRequestHeaders) {
            for (Entry<String, String> nameValue : op.getRequestHeaders().entrySet()) {
                String key = nameValue.getKey();
                if (!isXenonToXenon) {
                    if (Operation.REQUEST_CALLBACK_LOCATION_HEADER.equals(key)) {
                        isRequestWithCallback = true;
                        isXenonToXenon = true;
                    } else if (Operation.RESPONSE_CALLBACK_STATUS_HEADER.equals(key)) {
                        isXenonToXenon = true;
                    }
                }
                request.headers().set(nameValue.getKey(), nameValue.getValue());
            }
        }

        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(op.getContentLength()));
        request.headers().set(HttpHeaderNames.CONTENT_TYPE, op.getContentType());
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        if (!isXenonToXenon) {
            if (op.getCookies() != null) {
                String header = CookieJar.encodeCookies(op.getCookies());
                request.headers().set(HttpHeaderNames.COOKIE, header);
            }

            if (op.hasReferer()) {
                request.headers().set(HttpHeaderNames.REFERER, op.getRefererAsString());
            }

            request.headers().set(HttpHeaderNames.USER_AGENT, this.userAgent);
            if (op.getRequestHeader(Operation.ACCEPT_HEADER) == null) {
                request.headers().set(HttpHeaderNames.ACCEPT, Operation.MEDIA_TYPE_EVERYTHING_WILDCARDS);
            }

            request.headers().set(HttpHeaderNames.HOST, op.getUri().getHost());
        }

        boolean doCookieJarUpdate = !isXenonToXenon;
        boolean stopTracking = !isRequestWithCallback;
        op.nestCompletion((o, e) -> {
            if (e != null) {
                fail(e, op, originalBody);
                return;
            }

            if (stopTracking) {
                stopTracking(op);
            }

            if (doCookieJarUpdate) {
                updateCookieJarFromResponseHeaders(o);
            }

            // After request is sent control is transferred to the
            // NettyHttpServerResponseHandler. The response handler will nest completions
            // and call complete() when response is received, which will invoke this completion
            op.complete();
        });

        op.getSocketContext().writeHttpRequest(request);
    } catch (Throwable e) {
        op.setBody(ServiceErrorResponse.create(e, Operation.STATUS_CODE_BAD_REQUEST,
                EnumSet.of(ErrorDetail.SHOULD_RETRY)));
        fail(e, op, originalBody);
    }
}

From source file:com.whizzosoftware.foscam.camera.protocol.Order.java

License:Open Source License

public ByteBuf toByteBuf() {
    ByteBuf b = Unpooled.buffer(23 + text.length);

    // add "camera operate protocol"
    b.writeByte('M');
    b.writeByte('O');
    b.writeByte('_');
    b.writeByte('I');

    // add "operation code"
    b.writeByte(operationCode);/* ww w .  j a v a2  s  . c  o  m*/
    b.writeByte(0);

    // add reserve (INT8)
    b.writeByte(0);

    // add reserve (BINARY_STREAM[8])
    for (int i = 7; i <= 14; i++) {
        b.writeByte(0);
    }

    // add text length
    b.writeByte((byte) (text.length & 0xFF));
    b.writeByte((byte) ((text.length >> 8) & 0xFF));
    b.writeByte((byte) ((text.length >> 16) & 0xFF));
    b.writeByte((byte) ((text.length >> 24) & 0xFF));

    // add reserve (INT32)
    for (int i = 19; i <= 22; i++) {
        b.writeByte(0);
    }

    b.writeBytes(text);

    return b;
}