Example usage for io.netty.buffer Unpooled EMPTY_BUFFER

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

Introduction

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

Prototype

ByteBuf EMPTY_BUFFER

To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.

Click Source Link

Document

A buffer whose capacity is 0 .

Usage

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransportTest.java

License:Open Source License

@Test
public void testConnectionCounter() throws Exception {
    final Configuration configuration = new Configuration(
            ImmutableMap.of("bind_address", "127.0.0.1", "port", 0));
    final AbstractTcpTransport transport = new AbstractTcpTransport(configuration, throughputCounter,
            localRegistry, eventLoopGroup, eventLoopGroupFactory, nettyTransportConfiguration) {
    };//w  ww  . j av  a 2s  . c om
    transport.launch(input);

    await().atMost(5, TimeUnit.SECONDS).until(() -> transport.getLocalAddress() != null);
    final InetSocketAddress localAddress = (InetSocketAddress) transport.getLocalAddress();
    assertThat(localAddress).isNotNull();

    final ChannelFuture future1 = clientChannel(localAddress.getHostString(), localAddress.getPort()).channel()
            .writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE)
            .syncUninterruptibly();
    final ChannelFuture future2 = clientChannel(localAddress.getHostString(), localAddress.getPort()).channel()
            .writeAndFlush(Unpooled.EMPTY_BUFFER).syncUninterruptibly();

    // TODO: Get rid of this (arbitrary) wait time
    Thread.sleep(100L);

    assertThat(future1.channel().isActive()).isFalse();
    assertThat(future2.channel().isActive()).isTrue();
    assertThat(localRegistry.getGauges().get("open_connections").getValue()).isEqualTo(1);
    assertThat(localRegistry.getGauges().get("total_connections").getValue()).isEqualTo(2L);

    future2.channel().close().syncUninterruptibly();

    // TODO: Get rid of this (arbitrary) wait time
    Thread.sleep(100L);

    assertThat(future1.channel().isActive()).isFalse();
    assertThat(future2.channel().isActive()).isFalse();
    assertThat(localRegistry.getGauges().get("open_connections").getValue()).isEqualTo(0);
    assertThat(localRegistry.getGauges().get("total_connections").getValue()).isEqualTo(2L);
}

From source file:org.graylog2.plugin.inputs.util.ConnectionCounterTest.java

License:Open Source License

@Test
public void testConnectAndDisconnect() throws Exception {
    // Fresh channel, no connections so far
    assertThat(connectionCounter.getTotalConnections()).isEqualTo(0L);
    assertThat(connectionCounter.getConnectionCount()).isEqualTo(0);

    final EventLoopGroup clientEventLoopGroup = new NioEventLoopGroup(1);
    try {/*ww w  .j a va2  s.co m*/
        final ChannelFuture connectFuture = new Bootstrap().group(clientEventLoopGroup)
                .channel(NioSocketChannel.class).handler(new LoggingHandler())
                .localAddress(InetAddress.getLocalHost(), 0).connect(serverChannel.localAddress()).sync();
        final Channel clientChannel = connectFuture.channel();

        assertThat(clientChannel.isWritable()).isTrue();
        clientChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).syncUninterruptibly();

        // One client active
        assertThat(connectionCounter.getTotalConnections()).isEqualTo(1L);
        assertThat(connectionCounter.getConnectionCount()).isEqualTo(1);

        clientChannel.close().syncUninterruptibly();
    } finally {
        clientEventLoopGroup.shutdownGracefully();
        clientEventLoopGroup.awaitTermination(1, TimeUnit.SECONDS);
    }

    // No client, but 1 connection so far
    assertThat(connectionCounter.getTotalConnections()).isEqualTo(1L);
    assertThat(connectionCounter.getConnectionCount()).isEqualTo(0);
}

From source file:org.iotivity.cloud.base.protocols.http.HCProxyProcessor.java

License:Open Source License

/**
 * This function returns a created HTTP response
 * translated from the CoAP response.//from w  ww.j  a v a2 s  .c  o  m
 * 
 * @param response
 * @return httpResponse
 */
public HttpResponse getHttpResponse(IResponse response) {

    HttpResponse httpResponse = null;

    ResponseStatus coapResponseStatus = response.getStatus();
    ContentFormat coapContentFormat = response.getContentFormat();
    byte[] coapPayload = response.getPayload();
    boolean isPayload = false;

    HttpVersion httpVersion = HttpVersion.HTTP_1_1;

    if (coapPayload != null && coapPayload.length > 0) {

        isPayload = true;

        HttpResponseStatus httpStatus = getHttpResponseStatus(coapResponseStatus, isPayload);

        String httpContentType = null;

        ByteBuf httpContent = Unpooled.EMPTY_BUFFER;

        if (coapContentFormat == ContentFormat.APPLICATION_CBOR) {

            // Content-Type: application/json
            httpContentType = APPLICATION_JSON;

            String payloadString = null;
            try { // Cbor: Map to JSON string

                if (getTargetCoapPath().contains(DISCOVER_URI)) {
                    Log.v("Cbor decoding using ArrayList.class");
                    ArrayList<Object> cborMap = mStackCborArray.parsePayloadFromCbor(coapPayload,
                            ArrayList.class);
                    ObjectMapper cborMapper = new ObjectMapper();
                    payloadString = cborMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cborMap);
                } else {
                    Log.v("Cbor decoding using HashMap.class");
                    HashMap<String, Object> cborMap = mStackCborMap.parsePayloadFromCbor(coapPayload,
                            HashMap.class);
                    ObjectMapper cborMapper = new ObjectMapper();
                    payloadString = cborMapper.writerWithDefaultPrettyPrinter().writeValueAsString(cborMap);
                }

            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            if (payloadString == null || payloadString.trim().equalsIgnoreCase("null")) {
                payloadString = "";
            }

            byte[] payloadBytes = payloadString.getBytes();

            httpContent = Unpooled.wrappedBuffer(payloadBytes);

        } else {

            if (response instanceof CoapResponse) {
                // Content-Type:
                // application/coap-payload;cf=<Content-Format value>
                httpContentType = COAP_FORMAT_TYPE + ((CoapResponse) response).getContentFormatValue();
            } else {
                httpContentType = coapContentFormat.toString();
            }

            httpContent = Unpooled.wrappedBuffer(coapPayload);
        }

        httpResponse = new DefaultFullHttpResponse(httpVersion, httpStatus, httpContent);

        // Default: Non-persistent connection
        httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);

        httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, httpContentType);
        httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpContent.readableBytes());

        byte[] bytes = new byte[httpContent.readableBytes()];
        httpContent.getBytes(httpContent.readerIndex(), bytes);

        StringBuilder contentStrBuilder = new StringBuilder(new String(bytes));
        mCtx.channel().attr(HCProxyProcessor.ctxStrContent).set(contentStrBuilder);

    } else {

        isPayload = false;

        HttpResponseStatus httpStatus = getHttpResponseStatus(coapResponseStatus, isPayload);

        httpResponse = new DefaultFullHttpResponse(httpVersion, httpStatus);

        // Default: Non-persistent connection
        httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);

        // Some clients requires content-length=0
        // to decide a proper size of one response message.
        httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.NONE);
        httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO);
    }

    /*
     * If HTTP request was sign-in and HTTP response is 200 OK,
     * then set HTTP Cookie in the response for the session.
     */
    if (mTargetCoapPath != null && mTargetCoapPath.contains(SIGNIN_URI)
            && httpResponse.status() == HttpResponseStatus.OK) {
        long timeoutSeconds = SESSION_TIMEOUT;
        String createdSid = setSessionId(httpResponse, timeoutSeconds);

        // Set SessionExpiredTime in HttpDevice
        // and put it into httpDeviceMap using the session id as a key
        Device device = mCtx.channel().attr(ServerSystem.keyDevice).get();
        if (device != null) {
            ((HttpDevice) device).setSessionExpiredTime(timeoutSeconds);
            HttpServer.httpDeviceMap.put(createdSid, (HttpDevice) device);
            mCtx.channel().attr(ServerSystem.keyDevice).set(device);
        }
    }

    // Put HttpDevice into httpDeviceMap using the session id as a key
    HttpDevice httpDevice = (HttpDevice) mCtx.channel().attr(ServerSystem.keyDevice).get();
    if (httpDevice != null && mSessionId != null) {
        HttpServer.httpDeviceMap.put(mSessionId, httpDevice);
    }

    return httpResponse;
}

From source file:org.jooby.internal.netty.NettyPush.java

License:Apache License

@Override
public void push(final String method, final String path, final Map<String, Object> headers) {
    ctx.channel().eventLoop().execute(() -> {
        AsciiString streamIdHeader = HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text();
        Http2Connection connection = encoder.connection();
        int nextStreamId = connection.local().incrementAndGetNextStreamId();
        Http2Headers h2headers = new DefaultHttp2Headers().path(path).method(method).authority(authority)
                .scheme(scheme);/*from   w  ww  .  ja va 2s . c  o m*/
        headers.forEach((n, v) -> h2headers.add(n, v.toString()));
        encoder.writePushPromise(ctx, streamId, nextStreamId, h2headers, 0, ctx.newPromise());

        // TODO: Is there another way of handling a push promise?
        DefaultFullHttpRequest pushRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.valueOf(method.toUpperCase()), path, Unpooled.EMPTY_BUFFER,
                new DefaultHttpHeaders(false).set(streamIdHeader, nextStreamId), EmptyHttpHeaders.INSTANCE);
        ctx.pipeline().fireChannelRead(pushRequest);
        ctx.pipeline().fireChannelReadComplete();
    });
}

From source file:org.legacy.network.protocol.messages.CreationResponseMessage.java

License:Open Source License

public CreationResponseMessage(int status) {
    this.status = status;
    this.payload = Unpooled.EMPTY_BUFFER;
}

From source file:org.legacy.network.protocol.messages.LoginResponseMessage.java

License:Open Source License

public LoginResponseMessage(int status) {
    this.status = status;
    this.payload = Unpooled.EMPTY_BUFFER;
}

From source file:org.opendaylight.protocol.bgp.inet.Ipv6BgpPrefixSidParserTest.java

License:Open Source License

@Test(expected = IllegalArgumentException.class)
public void testWrongTlvType() {
    this.handler.serializeBgpPrefixSidTlv(new BgpPrefixSidTlv() {
        @Override/*from  ww w.j  av  a  2 s.c  o m*/
        public Class<? extends DataContainer> getImplementedInterface() {
            return BgpPrefixSidTlv.class;
        }
    }, Unpooled.EMPTY_BUFFER);
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.open.BgpExtendedMessageCapabilityHandler.java

License:Open Source License

@Override
public void serializeCapability(final CParameters capability, final ByteBuf byteAggregator) {
    final BgpExtendedMessageCapability bgpExtendedMessageCapability = capability
            .getBgpExtendedMessageCapability();
    if (bgpExtendedMessageCapability != null) {
        CapabilityUtil.formatCapability(CODE, Unpooled.EMPTY_BUFFER, byteAggregator);
    }//from w w w . jav a 2s. c o  m
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.open.RouteRefreshCapabilityHandler.java

License:Open Source License

@Override
public void serializeCapability(final CParameters capability, final ByteBuf byteAggregator) {
    if (capability == null || (capability.getAugmentation(CParameters1.class) == null)
            || (capability.getAugmentation(CParameters1.class).getRouteRefreshCapability() == null)) {
        return;/*from  ww w. j a  v a 2s  .  c o m*/
    }
    CapabilityUtil.formatCapability(CODE, Unpooled.EMPTY_BUFFER, byteAggregator);
}

From source file:org.opendaylight.protocol.bgp.parser.impl.message.update.AigpAttributeParser.java

License:Open Source License

/**
 * Transform AIGP attribute data from instance of Aigp class into byte buffer representation.
 *
 * @param aigp/* www .j  a va 2 s  .  co  m*/
 *          instance of Aigp class
 * @return
 *          byte buffer representation or empty buffer if AIGP TLV is null
 */
private static ByteBuf serializeAigpTLV(final Aigp aigp) {
    final AigpTlv tlv = aigp.getAigpTlv();
    if (tlv == null) {
        return Unpooled.EMPTY_BUFFER;
    }
    final ByteBuf value = Unpooled.buffer(AIGP_TLV_SIZE);
    value.writeByte(AIGP_TLV_TYPE);
    value.writeShort(AIGP_TLV_SIZE);
    value.writeLong(tlv.getMetric().getValue().longValue());
    return value;
}